/**
 * 功能功能  核心功能
 */

/**
 * 核心功能
 */
var gis_core = {
    map: null, //地图
    initconfig: null, //初始化配置信息
    isEnableMapClick: true,//是否加载地图点击事件
    extentChanges: new KeyValues(), //地图改变事件
    mapClicks: new KeyValues(),//地图点击事件
    //mapMouseMove:new KeyValues(),//地图鼠标移动事件
    //mapMouseOut:new KeyValues(),//地图鼠标移动事件
    mapLayers: new KeyValues(), //图层信息
    mapExtentDelta: null, //地图改变参数
    pluginList: new KeyValues(), //模块列表
    mapoaded: null,//地图加载完成
    /**
     * 地图初始化
     * @param completedCallback 地图加载完成后调用
     */
    initMap: function (completedCallback) {
        var core_features = [];
        core_features.push("esri/map");
        core_features.push("esri/layers/ArcGISTiledMapServiceLayer");
        core_features.push("esri/geometry/Extent");
        core_features.push("esri/SpatialReference");
        core_features.push("esri/layers/GraphicsLayer");
        core_features.push("plugin/TianDiTuVecLayer");
        core_features.push("plugin/TianDiTuCvaLayer");
        core_features.push("plugin/TianDiTuImgLayer");
        core_features.push("plugin/GaodeLayer");
        core_features.push("plugin/TianDiTuVecW3857Layer");
        core_features.push("esri/dijit/OverviewMap");
        core_features.push("dojo/domReady!");
        // 加载地图
        require(core_features, function (Map, ArcGISTiledMapServiceLayer, Extent, SpatialReference, GraphicsLayer, TianDiTuVecLayer, TianDiTuCvaLayer, TianDiTuImgLayer,
                                         GaodeLayer, TianDiTuVecW3857Layer, OverviewMap) {

            var map = new Map("map", {
                logo: false//, basemap: "topo"
            });
            gis_core.map = map;


            map.on("load", function () {
                //$("#map_zoom_slider").hide();
                //$(".esriAttributionList").hide();
                $("#map_zoom_slider").removeClass("esriSimpleSliderTL");
                $("#map_zoom_slider").css("right", "30px").css("bottom", "80px");

                $("#esri_dijit_OverviewMap_0").css("top", "55px").css("right", "20px")
                    .find(".ovwContainer")
                    .css("border-top", "1px solid #000").css("padding-top", "2px")
                    .css("border-right", "1px solid #000").css("padding-right", "2px")
                    .css("z-index", "0");

                if (gis_core.mapoaded != null) {
                    gis_core.mapoaded();
                }
            });
            //添加地图改变事件
            map.on("extent-change", function (delta) {
                gis_core.mapExtentDelta = delta;
                if (gis_core.extentChanges != undefined && gis_core.extentChanges.isEmpty != true && gis_core.extentChanges.getCount() > 0) {
                    for (var i = 0; i < gis_core.extentChanges.getCount(); i++) {
                        gis_core.extentChanges.values[i].value(delta);
                    }
                }
            });
            //添加地图点击事件
            map.on("click", function (delta) {
                if (gis_core.isEnableMapClick == true) {
                    if (gis_core.mapClicks != undefined && gis_core.mapClicks.isEmpty != true && gis_core.mapClicks.getCount() > 0) {
                        for (var i = 0; i < gis_core.mapClicks.getCount(); i++) {
                            gis_core.mapClicks.values[i].value(delta);
                        }
                    }
                }
            });
            // 添加底图
            var overviewMapLayer = "";
            if (gis_core.initconfig.isTransfer == "true") //服务端转包
            {
                /*var myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer("/mapaction");
                 map.addLayer(myTiledMapServiceLayer);
                 if (gis_core.initconfig.gisType == "tiandi") {
                 var myPoiTiledMapServiceLayer = new ArcGISTiledMapServiceLayer("/mappoiaction");
                 map.addLayer(myPoiTiledMapServiceLayer);
                 }*/

                var myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer("/mapservice/gistype_" + gis_core.initconfig.gisType);
                map.addLayer(myTiledMapServiceLayer);
                //myTiledMapServiceLayer.
                if (gis_core.initconfig.gisType == "tiandi") {
                    var myPoiTiledMapServiceLayer = new ArcGISTiledMapServiceLayer("/mappoiaction/gistype_" + gis_core.initconfig.gisType);
                    map.addLayer(myPoiTiledMapServiceLayer);
                }
                overviewMapLayer = myTiledMapServiceLayer;

            } else //不服务端转包
            {
                if (gis_core.initconfig.gisType == "tiandi") {
                    var vecLayer = new TianDiTuVecLayer();
                    map.addLayer(vecLayer);
                    var imgLayer = new TianDiTuImgLayer();
                    //map.addLayer(imgLayer);
                    var cvaLayer = new TianDiTuCvaLayer();
                    map.addLayer(cvaLayer);
                    overviewMapLayer = vecLayer;
                    //var vecwLayer = new TianDiTuVecW3857Layer();
                    //map.addLayer(vecwLayer);
                } else if (gis_core.initconfig.gisType == "baidu") {
                }
                else if (gis_core.initconfig.gisType == "arcgis") {
                    var myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer(gis_core.initconfig.arcgisurl);
                    map.addLayer(myTiledMapServiceLayer);
                    overviewMapLayer = myTiledMapServiceLayer;
                }
                else if (gis_core.initconfig.gisType == "gaode") {
                    var laye = new GaodeLayer();
                    map.addLayer(laye);

                    /*var laye_st = new GaodeLayer();
                     laye_st.layertype = "st";
                     map.addLayer(laye_st);*/

                    var laye_lable = new GaodeLayer();
                    laye_lable.layertype = "label";
                    map.addLayer(laye_lable);
                    overviewMapLayer = laye;
                }
            }

            if (myTiledMapServiceLayer != null) {
                var overviewMapDijit = new OverviewMap({
                    map: gis_core.map,
                    visible: false,
                    baseLayer: overviewMapLayer
                });
                overviewMapDijit.startup();
            }

            //初始化位置
            if (gis_common.stringIsNullOrWhiteSpace(gis_core.initconfig.extent) == false) {
                var extentarr = gis_core.initconfig.extent.split(',');
                var extent = new Extent(
                    parseFloat(extentarr[0]),
                    parseFloat(extentarr[1]),
                    parseFloat(extentarr[2]),
                    parseFloat(extentarr[3]),
                    new SpatialReference({
                        wkid: gis_core.initconfig.wkid
                    }));
                map.setExtent(extent);
            }
            //初始化图层
            for (var item in gis_common.layerIdList) {
                var l = gis_common.layerIdList[item];
                gis_core.addGraphicsLayerWithIndex(l.id, l.name, l.index);
            }

            if (completedCallback != undefined && completedCallback != null) {
                completedCallback();
            }
        });
    },
    /**
     * 地图加载完成之后
     */
    mapLoaded: function (callback) {
        gis_core.mapoaded = callback;
    },
    /**
     * 添加地图改变事件
     * @param key 关键字
     * @param extentChange 事件
     */
    addExtentChange: function (key, extentChange) {
        gis_core.extentChanges.setAt(key, extentChange);
    },
    /**
     * 移除地图改变事件
     * @param key
     */
    removeExtentChange: function (key) {
        gis_core.extentChanges.removeKey(key);
    },
    /**
     * 添加地图点击事件
     * @param key
     * @param click
     */
    addMapClick: function (key, click) {
        gis_core.mapClicks.setAt(key, click);
    },
    /**
     * 移除地图点击事件
     * @param key
     */
    removeClick: function (key) {
        gis_core.mapClicks.removeKey(key);
    },
    /**
     * 添加图形图层
     * @param layerid 图层ID
     * @param layerName 图层名称
     * @returns {返回图层对象}
     */
    addGraphicsLayer: function (layerid, layerName) {
        if (gis_core.mapLayers.containsKey(layerid)) {
            var l = gis_core.mapLayers.lookUp(layerid);
            l.value = layerName;
        } else {
            gis_core.mapLayers.setAt(layerid, layerName)
        }

        var layer = gis_core.getLayer(layerid);
        if (layer == null || layer == undefined) {
            layer = new esri.layers.GraphicsLayer();
            layer.id = layerid;
            gis_core.map.addLayer(layer);
        }
        return layer;
    },
    /**
     * 添加图形图层 带图层索引
     * @param layerid 图层id
     * @param layerName 图层名称
     * @param index 图层层级
     * @returns {返回图层对象}
     */
    addGraphicsLayerWithIndex: function (layerid, layerName, index) {
        if (gis_core.mapLayers.containsKey(layerid)) {
            var l = gis_core.mapLayers.lookUp(layerid);
            l.value = layerName;
        } else {
            gis_core.mapLayers.setAt(layerid, layerName)
        }

        var layer = gis_core.getLayer(layerid);
        if (layer == null || layer == undefined) {
            layer = new esri.layers.GraphicsLayer();
            layer.id = layerid;
            gis_core.map.addLayer(layer, index);
        }
        return layer;
    },
    /**
     * 添加图层 带回调函数
     * @param layerid 图层ID
     * @param layerName 图层名称
     * @param callback 回掉方法
     */
    addGraphicsLayerWithCallBack: function (layerid, layerName, callback) {
        if (gis_core.mapLayers.containsKey(layerid)) {
            var l = gis_core.mapLayers.lookUp(layerid);
            l.value = layerName;
        } else {
            gis_core.mapLayers.setAt(layerid, layerName)
        }

        var layer = gis_core.getLayer(layerid);
        if (layer == null || layer == undefined) {
            require(["esri/layers/GraphicsLayer", "dojo/domReady!"], function (GraphicsLayer) {
                layer = new GraphicsLayer();
                layer.id = layerid;
                gis_core.map.addLayer(layer);
                if (callback != null && callback != undefined) {
                    callback(layer);
                }
            });
        } else {
            callback(layer);
        }
    },
    /**
     * 插入通用图层
     * @param layerid 图层ID
     * @param layerName 图层名称
     * @param index  图层层级索引
     * @param layer  需要添加到地图上的图层
     */
    insertLayer: function (layerid, layerName, index, layer) {
        if (gis_core.mapLayers.containsKey(layerid)) {
            gis_core.removeLayer(layerid);
        }
        gis_core.mapLayers.setAt(layerid, layerName)
        gis_core.map.addLayer(layer, index);
    },
    insertLayerNoIndex: function (layerid, layerName, layer) {
        if (gis_core.mapLayers.containsKey(layerid)) {
            gis_core.removeLayer(layerid);
        }
        gis_core.mapLayers.setAt(layerid, layerName)
        gis_core.map.addLayer(layer);
    },
    /**
     * 移除图层
     * @param layerid 图层ID
     */
    removeLayer: function (layerid) {
        gis_core.mapLayers.removeKey(layerid);
        var layer = gis_core.getLayer(layerid);
        if (layer != null && layer != undefined) {
            gis_core.map.removeLayer(layer);
        }
    },
    /**
     * 获取图层
     * @param layerid 图层ID
     * @returns {图层对象}
     */
    getLayer: function (layerid) {
        var layer = gis_core.map.getLayer(layerid);
        if (layer == undefined || layer == null) {
            var ids = gis_core.map.graphicsLayerIds;
            if (ids == null || ids.length == 0) {
                return null;
            } else {
                for (var i = 0; i < ids.length; i++) {
                    if (gis_core.map.getLayer(ids[i]).id == layerid) {
                        layer = gis_core.map.getLayer(ids[i]);
                        break;
                    }
                }
            }
        }
        return layer;
    },
    /**
     * 添加模块
     * @param obj 模块对象
     */
    addPlugin: function (obj) {
        if (obj == null || obj == undefined) {
            return;
        }
        if (gis_core.pluginList.containsKey(obj.title.id)) {
            gis_core.pluginList.removeKey(obj.title.id);
        }
        //if (!gis_core.pluginList.containsKey(obj.title.id)) {
        gis_core.pluginList.setAt(obj.title.id, obj);
        //}
    },
    /**
     * 销毁所有模块 调用模块的 destroy() 方法
     */
    pluginDestroy: function () {
        for (var i = 0; i < gis_core.pluginList.getCount(); i++) {
            var plugin = gis_core.pluginList.values[i].value;
            if (plugin.hasOwnProperty("destroy")) {
                plugin.destroy();
            }
        }
        gis_core.pluginList.clear();
    },
    /**
     * 销毁模块（除了传入模块的ID）
     * @param pluginId 模块ID  title.id
     */
    pluginDestroyExceptId: function (pluginId) {
        var p = undefined;
        for (var i = 0; i < gis_core.pluginList.getCount(); i++) {
            var plugin = gis_core.pluginList.values[i].value;
            if (plugin.title.id == pluginId) {
                p = plugin;
            } else if (plugin.hasOwnProperty("destroy")) {
                plugin.destroy();
            }
        }
        gis_core.pluginList.clear();
        gis_core.addPlugin(p);
    },
    /**
     * 获取公用坐标系
     */
    getSpatialReference: function () {
        var spatialReference = new esri.SpatialReference({wkid: gis_core.initconfig.wkid});
        return spatialReference;
    }
};

/**
 * 面板布局
 */
var gis_layout = {
    /**
     * 工具栏创建布局
     * @param id 全局ID
     * @param obj 被点击的标签
     * @param width 面板宽度
     * @param divContent jquery 对象 (html代码)
     */
    createToolbar: function (id, obj, width, divContent) {
        var flag = $(obj).attr("flage");
        if ($(obj).attr("divid") == id) {
            if ($(obj).attr("flage") == "hide") {
                $("#" + id).show("fast");
                $(obj).attr('flage', "show");
            } else {
                $("#" + id).hide("fast");
                $(obj).attr('flage', "hide");
            }
        } else {
            /*var content = "";
             content = "<div id='" + id + "' class=\"tabs-modal\" style=\"width:" + width + "px;\">";
             content += "<div class=\"panel\"> <div class=\"panel-body\"><div class=\"form-horizontal\">";
             content += "</div></div></div></div>";*/

            var content = "";
            content = "<div id='" + id + "' class='tabs-modal' style='height:auto;width:" + width + "px; display:block;'>";
            content += " <div class='panel'>";
            content += "		<div class='panel-body'>";
            content += "			<div class='form-horizontal'>";
            content += "			</div>";
            content += "		</div>";
            content += "	</div>";
            content += "</div>";
            var div = $(content);
            div.find(".form-horizontal").append(divContent);
            $(obj).attr("divid", id);
            //$(obj).after(div);
            $(obj).attr('flage', "show");
            $(".toolbox-wrap").append(div);
        }
    },
    /**
     * 工具栏创建布局
     * @param id 全局ID
     * @param obj 被点击的标签
     * @param width 面板宽度
     * @param fun 方法  获取需要添加的jquery 对象 (html代码)
     */
    createToolbarWithFun: function (id, obj, width, fun) {
        var flag = $(obj).attr("flage");
        if ($(obj).attr("divid") == id) {
            if ($(obj).attr("flage") == "hide") {
                $("#" + id).show("fast");
                $(obj).attr('flage', "show");
            } else {
                $("#" + id).hide("fast");
                $(obj).attr('flage', "hide");
            }
        } else {
            fun(function (divContent) {
                /*var content = "";
                 content = "<div id='" + id + "' class=\"tabs-modal\" style=\"width:" + width + "px;max-height:300px;\">";
                 content += "<div class=\"panel\"> <div class=\"panel-body\"><div class=\"form-horizontal\">";
                 content += "</div></div></div></div>";
                 var div = $(content);
                 div.find(".form-horizontal").append(divContent);
                 $(obj).attr("divid", id);
                 $(obj).after(div);
                 $(obj).attr('flage', "show");*/

                var _width = $(".toolbox").width();
                var w = 0;
                var lis = $(".toolbar li");
                for (var i = 0; i < lis.length; i++) {
                    var o = $(lis[i]);
                    if (o.attr("did") == $(obj).attr("did")) {
                        break;
                    }
                    w = w + o.width();
                }

                var content = "";
                if (_width - w <= width) {
                    content = "<div id='" + id + "' class='tabs-modal' style='height:auto;width:" + width + "px; display:block;'>";
                }
                else {
                    content = "<div id='" + id + "' class='tabs-modal' style='height:auto;width:" + width + "px; left:" + w + "px;  display:block;'>";
                }
                content += " <div class='panel'>";
                content += "		<div class='panel-body'>";
                content += "			<div class='form-horizontal'>";
                content += "			</div>";
                content += "		</div>";
                content += "	</div>";
                content += "</div>";
                var div = $(content);
                div.find(".form-horizontal").append(divContent);
                $(obj).attr("divid", id);
                $(obj).attr('flage', "show");

                $(".toolbox-wrap").append(div);
                //$(".tabs-modal").append(div);

            });
        }
    },
    /**
     * 创建菜单（有弹出面板 fun获取jquery对象）
     * @param id 全局ID
     * @param obj 被点击的标签
     * @param title 菜单标题
     * @param fun 方法  获取需要添加的jquery 对象 (html代码)
     */
    createMenubarWithFun: function (id, obj, title, fun) {
        $("._menubar_item_isShow").hide("hide");

        if ($("#" + id).size() > 0) {
            if ($("#" + id).css("display") == "none") {
                $("#" + id).show("fast");
            } else {
                $("#" + id).hide("hide");
            }
        } else {
            fun(function (divContent) {
                $("#" + id).remove();
                var content = "";
                content += "<div id='" + id + "' class=\"modal-nav _menubar_item_isShow\">";
                content += "	<div class=\"panel\">";
                content += "		<div class=\"panel-heading\">" + title;
                content += " 			<button type=\"button\" class=\"minus\"><i class=\"fa fa-minus\"></i></button>";
                content += "		</div>";
                content += "		<div class=\"panel-body\"><div class=\"form-horizontal\">";
                content += "		</div></div>";
                content += "	</div>";
                content += "</div>";

                var div = $(content);
                div.find(".form-horizontal").append(divContent);

                div.find(".minus").bind("click", function (e) {
                    div.hide("fast");
                });
                div.find(".minus").bind("click", function (e) {
                });
                $("#div_menu").append(div);
            });
        }

    },
    /**
     * 创建菜单（无弹出面板）
     * @param id 全局ID
     * @param obj 被点击的标签
     * @param fun 方法  获取需要添加的jquery 对象 (html代码)
     */
    createMenubar: function (id, obj, fun) {
        if ($(obj).attr("divid") != id) {
            $(obj).attr('divid', id);
            var t = "<div id='circle_" + id + "' class=\"circle-staus\"></div>";
            $(obj).after($(t));
        }
        fun();
    },
    /**
     * 隐藏menubar
     * */
    hideMenubar: function () {
        $("._menubar_item_isShow").hide("hide");
    },
    /**
     * 创建图例
     * @param id 全局ID
     * @param title 图例标题
     * @param divContent  jquery 对象 (html代码)
     */
    createLegend: function (id, title, divContent) {
        $("#" + id).remove();

        var content = "<div id='" + id + "' class=\"legend\">";
        content += "<label class=\"legend-label\">" + title + "</label>";
        content += "</div>";

        var div = $(content);
        div.find(".legend-label").after(divContent);

        if ($(".toolbox > div:first").length > 0) {
            $(".toolbox > div:first").before(div);
        } else {
            $(".toolbox").append(div);
        }
    },
    /**
     * 移除图例
     * @param id
     */
    removeLegend: function (id) {
        if (id == undefined || id == null || gis_common.stringIsNullOrWhiteSpace(id)) {
            $(".legend").remove();
        }
        else {
            $("#" + id).remove();
        }
    },
    /**
     * 添加左边面板 如果ID相同，将移除之前面板
     * @param id 全局ID
     * @param title 标题
     * @param divContent jquery 对象 (html代码)
     * @param forbidClose 禁止关闭
     */
    createLeftWidget: function (id, title, divContent, forbidClose) {
        var add = false;
        var $div = $("#widget_left_content");
        if ($div == null || $div == undefined || $div.length == 0) {
            var content = "<div id='widget_left_content' class=\"pop-panel pop-left\" style='max-width: none'>";
            content += "	<div class=\"panel pop-tabs\">";
            content += "		<div id='widget_left_title' class=\"panel-tabs-nav\">";
            content += "			<ul id='widget_left_titels'>";
            content += "				<li class='tool-right'>";
            content += "					<button id='widget_left_close' type='button' title='关闭所有' class='close'><i class='fa fa-close'></i></button>";
            content += "					<button id='widget_left_min' type='button' title='最大化/最小化' class='close eye-small'><i class='fa fa-minus'></i></button>";
            content += "				</li>";
            content += "			<ul>";
            content += "		</div>";
            content += "		<div id='widget_left_body' class=\"panel-body\">";
            content += "			<div id='widget_left_contents' class=\"pop-content\" style=\"max-height:400px;overflow-y:auto;overflow:auto\">";
            content += "			</div>";
            content += "		</div>";
            content += "	</div>";
            content += "</div>";
            $div = $(content);
            //关闭所有
            if (forbidClose) {
                $div.find("#widget_left_close").remove();
            } else {
                $div.find("#widget_left_close").bind("click", function () {
                    $("#widget_left_content").remove();
                });
            }

            //最大最小化
            $div.find("#widget_left_min").bind("click", function () {
                var stat = $(this).attr("stat");
                if (stat == null || stat == "max") {
                    $("#widget_left_body").hide();
                    $(this).attr("stat", "min");
                }
                else {
                    $("#widget_left_body").show();
                    $(this).attr("stat", "max");
                }
            });
            add = true;
        } else {
            $div.find("#widget_left_title_" + id).remove();
            $div.find("#widget_left_content_" + id).remove();
            $div.find("#" + id).remove();
        }
        //添加标题
        var div_title_html = "<li id='widget_left_title_" + id + "' class=\"active _widget_left_title\">" +
            "<a href=\"javascript:void(0);\">" + title + "</a><button id='widget_left_item_close_" + id + "' " +
            "type='button' tid='" + id + "' title='关闭' class='close'>" +
            "<i class='fa fa-close'></i></button></li>";

        var $div_title = $(div_title_html);
        if (forbidClose) {
            $div.find("#widget_left_close").remove();
            $div_title.find("#widget_left_item_close_" + id).remove();
        } else {
            $div_title.find("#widget_left_item_close_" + id).bind("click", function () {
                var id = $(this).attr('tid');
                gis_layout.removeLeftWidget(id);
            });
        }

        $div.find("#widget_left_titels").append($div_title);
        //添加内容
        var div_content_html = "<div id='widget_left_content_" + id + "' class=\"wrap-cont show\"></div>";
        var $div_content = $(div_content_html);
        $div.find("#widget_left_contents").append($div_content);
        $div.find("#widget_left_content_" + id).append(divContent);
        divContent.attr("id", id);
        //点标题切换
        $div.find("#widget_left_title_" + id).bind("click", function () {
            $(this).addClass("active").siblings().removeClass("active");
            $div.find("#widget_left_content_" + id).addClass("show").removeClass("hidden").siblings().removeClass('show').addClass("hidden");
        });

        $div_title.click();

        if (add == true) {
            $(".map-main").append($div);
        }
    },
    /**
     * 根据ID移除左边面板tab，如果面板的tab都被移除了，就关闭左边侧面板
     * @param id
     */
    removeLeftWidget: function (id) {
        if (id == undefined || id == null || gis_common.stringIsNullOrWhiteSpace(id)) {
            $("#widget_left_content").remove();
            return;
        }
        //移除tab
        var $div = $("#widget_left_content");
        $div.find("#widget_left_title_" + id).remove();
        $div.find("#widget_left_content_" + id).remove();
        $div.find("#" + id).remove();
        //判断左边侧是否还有其他tag 如果没有 就关闭左边侧面板
        var $child = $div.find("#widget_left_contents").children();

        if ($child.length == 0) {
            $div.remove();
        } else {
            var $activeTitles = $div.find('._widget_left_title.active');
            if ($activeTitles.length == 0) {
                $div.find('._widget_left_title')[0].click();
            }
        }
    },
    /**
     * 添加右边面板 如果ID相同，将移除之前面板
     * @param id 全局ID
     * @param title 标题
     * @param divContent jquery 对象 (html代码)
     * @param forbidClose 禁止关闭
     */
    createRightWidget: function (id, title, divContent, forbidClose) {
        var add = false;
        var $div = $("#widget_right_content");
        if ($div == null || $div == undefined || $div.length == 0) {
            var content = "<div id='widget_right_content' class=\"pop-panel pop-right\">";
            content += "	<div class=\"panel pop-tabs\">";
            content += "		<div id='widget_right_title' class=\"panel-tabs-nav\">";
            content += "			<ul id='widget_right_titels'>";
            content += "				<li class='tool-right'>";
            content += "					<button id='widget_riget_close' type='button' title='关闭所有' class='close'><i class='fa fa-close'></i></button>";
            content += "					<button id='widget_riget_min' type='button' title='最大化/最小化' class='close eye-small'><i class='fa fa-minus'></i></button>";
            content += "				</li>";
            content += "			<ul>";
            content += "		</div>";
            content += "		<div id='widget_right_body' class=\"panel-body\">";
            content += "			<div id='widget_right_contents' class=\"pop-content\" style=\"max-height:400px;overflow-y:auto;\">";
            content += "			</div>";
            content += "		</div>";
            content += "	</div>";
            content += "</div>";
            $div = $(content);
            if (forbidClose) {
                $div.find("#widget_riget_close").remove();
            } else {
                //关闭所有
                $div.find("#widget_riget_close").bind("click", function () {
                    $("#widget_right_content").remove();
                });
            }

            //最大最小化
            $div.find("#widget_riget_min").bind("click", function () {
                var stat = $(this).attr("stat");
                if (stat == null || stat == "max") {
                    $("#widget_right_body").hide();
                    $(this).attr("stat", "min");
                }
                else {
                    $("#widget_right_body").show();
                    $(this).attr("stat", "max");
                }
            });
            add = true;
        } else {
            $div.find("#widget_right_title_" + id).remove();
            $div.find("#widget_right_content_" + id).remove();
            $div.find("#" + id).remove();
        }

        var div_title_html = "<li id='widget_right_title_" + id + "' class=\"active _widget_right_title\">" +
            "<a href=\"javascript:void(0);\">" + title + "</a>" +
            "<button id='widget_right_item_close_" + id + "' tid='" + id + "' type='button' title='关闭' class='close'>" +
            "<i class='fa fa-close'></i></button></li>";
        var $div_title = $(div_title_html);
        $div_title.find("#widget_right_item_close_" + id).bind("click", function () {
            var id = $(this).attr('tid');
            gis_layout.removeRightWidget(id);
        });
        $div.find("#widget_right_titels").append($div_title);

        var div_content_html = "<div id='widget_right_content_" + id + "' class=\"wrap-cont show\"></div>";
        var $div_content = $(div_content_html);
        $div.find("#widget_right_contents").append($div_content);
        $div.find("#widget_right_content_" + id).append(divContent);
        divContent.attr("id", id);

        if (forbidClose) {
            $div.find("#widget_riget_close").remove();
            $div.find("#widget_right_title_" + id).remove();
        } else {
            $div.find("#widget_right_title_" + id).bind("click", function () {
                $(this).addClass("active").siblings().removeClass("active");
                $div.find("#widget_right_content_" + id).addClass("show").removeClass('hidden').siblings().removeClass('show').addClass('hidden');
            });
        }


        $div_title.click();

        if (add == true) {
            $(".map-main").append($div);
        }
    },
    /**
     * 根据ID移除左边面板tab，如果面板的tab都被移除了，就关闭左边侧面板
     * @param id
     */
    removeRightWidget: function (id) {
        if (id == undefined || id == null || gis_common.stringIsNullOrWhiteSpace(id)) {
            $("#widget_right_content").remove();
            return;
        }
        //移除tab
        var $div = $("#widget_right_content");
        $div.find("#widget_right_title_" + id).remove();
        $div.find("#widget_right_content_" + id).remove();
        $div.find("#" + id).remove();
        //判断左边侧是否还有其他tag 如果没有 就关闭左边侧面板
        var $child = $div.find('#widget_right_contents').children();
        if ($child.length == 0) {
            $div.remove();
        } else {
            var $activeTitles = $div.find('._widget_right_title.active');
            if ($activeTitles.length == 0) {
                $div.find('._widget_right_title')[0].click();
            }
        }
    },
    /**
     * 添加其他面板 框架不做任何操作 如果ID相同，将移除之前面板
     * @param id
     * @param fun 方法  获取需要添加的jquery 对象 (html代码)
     */
    createOtherWidget: function (id, fun) {
        var mapMain = $(".map-main");
        mapMain.find("#" + id).remove();
        fun(function (divContent) {
            divContent.attr("id", id);
            mapMain.append(divContent);
        });
    }
};

/**
 * 通用功能
 */
var gis_common = {
    isLoadingCount: 0,
    poi: null,
    res: null, //资源显示
    scene: null,//场景
    commonQuery: null, //通用查询
    distance: null,//测距
    queryFunList: new KeyValues(), //通用查询，模块注册方法
    /**
     * 错误 异常信息显示
     * @param error 错误信息
     */
    showError: function (error) {
        alert(error);
    },
    /**
     * 信息显示
     * @param msg
     */
    showMessage: function (msg) {
        alert(msg);
    },
    /**
     * 统一处理错误信息，错误码
     * @param output
     */
    outPut: function (output, callback) {
        var o = output;
        if (typeof(output) != "object") {
            try {
                o = eval("(" + output + ")");
            }
            catch (exception) {
                gis_common.showError("output 在转换成对象时候出差：" + exception);
                return;
            }
        }

        if (o == null || o == undefined) {
            gis_common.showError("返回对象为空！");
            return
        }
        if (o.errorCode == -1001) {
            window.location.href = "/index.jsp";
        }
        else if (o.errorCode != 0 || !gis_common.stringIsNullOrWhiteSpace(o.errorMessage)) {
            gis_common.showError(o.errorMessage);
        }
        else {
            callback(o.data);
        }
    },
    /**
     * 显示Loading
     */
    mapLoadingShow: function () {
        $(".map-main").loading();
        //$("html").loading();
    },
    /**
     * 隐藏Loading
     */
    mapLoadingHide: function () {
        $(".map-main").loading("close");
        //$("html").loading("close");
    },
    /**
     * 显示Loading  以计数器的方式控制 计数器加1
     */
    isLoadingAddCount: function () {
        if (gis_common.isLoadingCount == 0) {
            gis_common.mapLoadingShow();
        }
        gis_common.isLoadingCount = gis_common.isLoadingCount + 1;
    },
    /**
     * Loading 计算减1 如果计数器为0  就关闭Loading
     */
    isLoadingSunCount: function () {
        gis_common.isLoadingCount = gis_common.isLoadingCount - 1;
        if (gis_common.isLoadingCount <= 0) {
            gis_common.mapLoadingHide();
            gis_common.isLoadingCount = 0;
        }
    },
    /**
     * 判断字符串是否为空 undefined null ""
     * @param str 需要判断的字符串
     * @returns {undefined、null、 "" 返回true 其他返回false }
     */
    stringIsNullOrWhiteSpace: function (str) {
        if (str == undefined || str == null || str == "" || str.length == 0) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 打开窗口 用来下载文件 等
     * @param url
     * @param target
     */
    windowOpen: function (url, target) {
        var a = document.createElement("a");
        a.setAttribute("href", url);
        if (target == null) {
            target = '';
        }

        a.setAttribute("target", target);
        document.body.appendChild(a);
        if (a.click) {
            a.click();
        } else {
            try {
                var evt = document.createEvent('Event');
                a.initEvent('click', true, true);
                a.dispatchEvent(evt);
            } catch (e) {
                window.open(url);
            }
        }
        document.body.removeChild(a);
    },
    /**
     * 显示当前地图范围
     */
    showMapExtent: function () {
        alert("xmax:" + gis_core.map.extent.xmax + " ymax:" + gis_core.map.extent.ymax + " xmin:" + gis_core.map.extent.xmin + " ymin:" + gis_core.map.extent.ymin + " level:" + gis_core.map.getLevel());
    },
    /**
     *设置地图显示范围
     * @param xmax
     * @param ymax
     * @param xmin
     * @param ymin
     */
    setExtent: function (xmax, ymax, xmin, ymin) {
        //var extent = new esri.geometry.Extent(parseFloat(xmin), parseFloat(ymin), parseFloat(xmax), parseFloat(ymax), gis_core.initconfig.wkid);
        var spatialReference = new esri.SpatialReference({wkid: gis_core.initconfig.wkid});
        var extent = new esri.geometry.Extent(parseFloat(xmin), parseFloat(ymin), parseFloat(xmax), parseFloat(ymax), spatialReference);
        gis_core.map.setExtent(extent);
    },
    /**
     *设置地图中心点,并添加缩放比例
     * @param lon   经度
     * @param lat   维度
     * @param zoom  缩放比例
     */
    setExtentByPoint: function (lon, lat, zoom) {
        //var extent = new esri.geometry.Extent(parseFloat(xmin), parseFloat(ymin), parseFloat(xmax), parseFloat(ymax), gis_core.initconfig.wkid);
        var spatialReference = new esri.SpatialReference({wkid: gis_core.initconfig.wkid});
        gis_common.setExtent(parseFloat(lon) + 0.001 * parseFloat(zoom), parseFloat(lat) + 0.001 * parseFloat(zoom), parseFloat(lon) - 0.001 * parseFloat(zoom), parseFloat(lat) - 0.001 * parseFloat(zoom));
    },
    /**
     * 根据点定位
     * @param lon
     * @param lat
     */
    setPoint: function (lon, lat) {
        gis_common.queryInit();
        gis_common.commonQuery.setPoint(lon, lat);
    },
    /**
     * 显示当前地图范围
     * @returns {返回Extent对象}
     */
    getMapExtent: function () {
        var obj = {};
        obj.xMin = gis_core.map.extent.xmin;
        obj.xMax = gis_core.map.extent.xmax;
        obj.yMin = gis_core.map.extent.ymin;
        obj.yMax = gis_core.map.extent.ymax;
        obj.level = gis_core.map.getLevel();
        if (gis_core.mapExtentDelta != null) {
            obj.resolution = gis_core.mapExtentDelta.lod.resolution;
        }
        obj.wkid = gis_core.map.spatialReference.wkid;
        //obj.wkid = gis_core.initconfig.wkid;
        //var json= $.toJSON(obj);
        return obj;
    },
    /**
     * 获取URL参数
     */
    getQueryString: function (key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return (r[2]);
        return null;
    },
    /**
     * 根据 delta 获取 Extent 的json 对象
     * @param delta
     */
    getMapExtentDelta: function (delta) {
        var obj = {};
        obj.xMin = delta.extent.xmin;
        obj.xMax = delta.extent.xmax;
        obj.yMin = delta.extent.ymin;
        obj.yMax = delta.extent.ymax;
        obj.level = delta.lod.level;
        obj.resolution = delta.lod.resolution;
        obj.wkid = gis_core.map.spatialReference.wkid;
        return $.toJSON(obj);
    },
    /**
     * 生成基站图形
     * @param bts
     * @returns {返回Graphic对象}
     */
    createBtsGraphic: function (bts) {
        var graphics = [];
        var point = new esri.geometry.Point(bts.longitude, bts.latitude, gis_core.getSpatialReference());
        var attr = {
            "data": bts,
            "name": bts.name
        };
        var symbol = new esri.symbol.PictureMarkerSymbol('/images/cluster.png', 48, 48);

        if (bts.tag == "cluster") {
            var text = bts.value + "";
            if (bts.value >= 10000) {
                text = (bts.value / 10000).toFixed(2) + "万"
            }
            var textSymbol = new esri.symbol.TextSymbol(text);
            textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_MIDDLE);
            textSymbol.setColor(new esri.Color([255, 255, 255, 1]));
            textSymbol.setOffset(0, -5);
            var textgraphic = new esri.Graphic(point, textSymbol, attr);
            graphics.push(textgraphic);

        } else if (bts.resType == "LTECELL") {
            symbol = new esri.symbol.PictureMarkerSymbol('/images/lte.png', 28, 28);
            // symbol = new esri.symbol.PictureMarkerSymbol('/images/demo.png', 28, 28);

        } else if (bts.resType == "GSMCELL") {
            symbol = new esri.symbol.PictureMarkerSymbol('/images/gsm.png', 28, 28);

        } else if (bts.resType == "TDCELL") {
            symbol = new esri.symbol.PictureMarkerSymbol('/images/td.png', 28, 28);
        } else if (bts.resType == "ENODEB") {
            var
            symbol = new esri.symbol.PictureMarkerSymbol('/images/LTE-' + bts.warnType + '.png', 26, 31);
        } else if (bts.resType == "BTS") {
            symbol = new esri.symbol.PictureMarkerSymbol('/images/BTS-' + bts.warnType + '.png', 26, 31);
        } else if (bts.resType == "OLT") {
            symbol = new esri.symbol.PictureMarkerSymbol('/images/OLT-' + bts.warnType + '.png', 26, 31);
        }

        var graphic = new esri.Graphic(point, symbol, attr);
        graphics.push(graphic);

        graphics = graphics.reverse();
        return graphics;
    },
    /**
     * 生成小区图形
     * @param cell 小区对象
     * @returns {返回Graphic对象}
     */
    createCellGraphic: function (cell) {
        var attr = {
            "data": cell,
            "name": cell.name
        };

        var rings = gis_common.createCellCoverRing(cell.longitude, cell.latitude, cell.radius, cell.azimuth, cell.antbw);
        //var polygon = new esri.geometry.Polygon(gis_core.map.spatialReference);
        var polygon = new esri.geometry.Polygon(gis_core.initconfig.wkid);
        polygon.addRing(rings);

        var symbol = new esri.symbol.SimpleFillSymbol();
        symbol.setColor(new esri.Color([180, 168, 192, 150]));
        symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([200, 112, 181, 207]), 1));

        var graphic = new esri.Graphic(polygon, symbol, attr);
        return graphic;
    },
    /**
     * 生成小区覆盖
     * @param longitude 经度
     * @param latitude 纬度
     * @param radius 半径
     * @param azimuth  方向角(0度为正北,顺时针旋转)
     * @param antbw 半功率角(小区覆盖角度的一半)
     * @returns {返回经纬度数组}
     */
    createCellCoverRing: function (longitude, latitude, radius, azimuth, antbw) {
        var ring = [];
        var startAngle = azimuth - antbw;
        var sweepAngle = antbw * 2;
        var centerPoint = {
            'lat': latitude,
            'lon': longitude
        };
        if (gis_core.initconfig.wkid == 4326) {
            centerPoint = GPS.mercator_encrypt(latitude, longitude);
        }

        ring.push([longitude, latitude]);
        for (var i = startAngle; i < startAngle + sweepAngle; i += 5) {
            var degree = i / 180.0 * Math.PI;
            var x = centerPoint.lon + Math.sin(degree) * radius;
            var y = centerPoint.lat + Math.cos(degree) * radius;

            if (gis_core.initconfig.wkid == 4326) {
                var temp = GPS.mercator_decrypt(y, x);
                ring.push([temp.lon, temp.lat]);
            } else {
                ring.push([x, y]);
            }
        }
        ring.push([longitude, latitude]);

        return ring;
    },
    /**
     * 生成小区示意图形
     * @param btses
     * @returns {Array}
     */
    createCellCover: function (btses, radius) {
        var r = 30;
        if (radius != null && radius != undefined) {
            r = radius;
        }
        var graphics = [];
        for (var i = 0; i < btses.length; i++) {
            var bts = btses[i];
            if (bts.tag == "cluster") {
                var attr = {
                    "data": bts,
                    "cluster": true
                };
                var point = new esri.geometry.Point(bts.longitude, bts.latitude, gis_core.getSpatialReference());

                var symbol = new esri.symbol.PictureMarkerSymbol('/images/cluster.png', 48, 48);
                var graphic = new esri.Graphic(point, symbol, attr);
                graphics.push(graphic);

                var text = bts.value + "";
                if (bts.value >= 10000) {
                    text = (bts.value / 10000).toFixed(2) + "万"
                }
                var textSymbol = new esri.symbol.TextSymbol(text);
                textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_MIDDLE);
                textSymbol.setColor(new esri.Color([255, 255, 255, 1]));
                textSymbol.setOffset(0, -5);
                var textgraphic = new esri.Graphic(point, textSymbol, attr);
                graphics.push(textgraphic);
            }
            else {
                var antbw = 30;
                var azimuth = 0;
                var off_azimuth = 0;
                if (bts.cells.length > 1) {
                    antbw = 180.0 / bts.cells.length;
                    off_azimuth = 360.0 / bts.cells.length;
                }
                if (antbw > 30) {
                    antbw = 30;
                }

                for (var j = 0; j < bts.cells.length; j++) {
                    var cell = bts.cells[j];
                    cell.radius = r;
                    cell.antbw = antbw;
                    if (cell.azimuth == 0) {
                        cell.azimuth = azimuth;
                    }
                    var g = gis_common.createCellGraphic(cell);
                    graphics.push(g);
                    azimuth = azimuth + off_azimuth;
                }
            }
        }
        graphics = graphics.reverse();
        return graphics;
    },
    /**
     * 生成KeyValse 形式的list 的列表
     * @param keyValues
     * @returns {*|jQuery|HTMLElement}
     */
    createKeyValueList: function (keyValues) {
        /*var content = "<ul class='panel-list'>";
         if (keyValues == null || keyValues == undefined || keyValues.length == 0) {
         content += "<div>无数据</div>";
         }
         else {
         content += "<table class='table'>";

         for (var i = 0; i < keyValues.length; i++) {
         var keyvalue = keyValues[i];
         content += "<tr>";
         content += "    <td align='right'>";
         content += "        <span class='list-label'>" + keyvalue.id + ":</span>";
         content += "    <td>";
         content += "    <td  align='left'>";
         content += "        <span>" + keyvalue.name + "</span>";
         content += "    <td>";
         content += "</tr>";
         }

         content += "</table>";
         }
         content += "</ul>";
         var div = $(content);
         return div;*/

        var content = "<div class='pop-content'>";
        content += "<div class='form-hor-cont'>";
        content += "	<div class='form-horizontal text-align-lr' style='width: 300px;'>";

        if (keyValues == null || keyValues == undefined || keyValues.length == 0) {
            content += "<div>无数据</div>";
        } else {
            content += "<div class='form-group'>";
            for (var i = 0; i < keyValues.length; i++) {
                var keyvalue = keyValues[i];
                /*if (i % 2 == 0) {
                 content += "<div class='col-sm-7' style='background-color: #DADADA;'><label class='control-label' style='height: 30px;'>" + keyvalue.id + "</label></div>";
                 content += "<div class='col-sm-5' style='background-color: #DADADA;'><p class='form-control-static'>" + keyvalue.name + "</p></div>";
                 }
                 else{*/
                content += "<div class='col-sm-7'><label class='control-label'>" + keyvalue.id + "</label></div>";
                content += "<div class='col-sm-5'><p class='form-control-static'>" + keyvalue.name + "</p></div>";
                //}
            }
            content += "</div>";
        }

        content += "	</div>";
        content += "	</div>";
        content += "</div>";
        var div = $(content);
        return div;

    },
    /**
     * 通用查询 注册查询方法
     * @param key
     * @param fun 查询方法
     */
    queryRegisterFun: function (key, fun) {
        if (!gis_common.queryFunList.containsKey(key)) {
            gis_common.queryFunList.setAt(key, fun);
        }
    },
    /**
     * 通用查询 移除查询方法
     * @param key
     * @param fun
     */
    queryRemoveFun: function (key, fun) {
        if (gis_common.queryFunList.containsKey(key))
            gis_common.queryFunList.removeKey(key);
    },
    /**
     * 通用查询方法  点 定位
     */
    queryPointFun: function (obj) {
        gis_common.queryInit();
        gis_layout.createToolbarWithFun("commonquery_queryPointFun_param_div", obj, 320, gis_common.commonQuery.showPointHtml);
    },
    /**
     * 通用查询 初始化方法
     */
    query: function () {
        gis_common.queryInit();
        gis_common.commonQuery.query();
    },
    /**
     * 通用查询  初始化
     */
    queryInit: function () {
        if (gis_common.commonQuery == null) {
            gis_common.commonQuery = new CommonQuery();
            gis_common.commonQuery.init();
        }
    },
    /**
     * Poi查询
     */
    poiLoad: function (obj, showCate) {
        if (gis_common.poi == null) {
            gis_common.poi = new Poi();
        }
        gis_common.poi.init(obj, showCate);
    },
    /**
     * Poi销毁
     */
    poiDestroy: function () {
        if (gis_common.poi != null) {
            {
                gis_common.poi.Destroy();
            }
            gis_common.poi = null;
        }
    },
    /**
     * 资源res
     */
    resLoad: function (obj) {
        if (gis_common.res == null) {
            gis_common.res = new Res();
            gis_common.res.init();
        }
        gis_layout.createToolbarWithFun("res_param_div", obj, 320, gis_common.res.createParamDiv);
    },
    /**
     *自定义资源查询参数
     */
    resSetQueryParam: function (rqCell) {
        if (gis_common.res == null) {
            gis_common.res = new Res();
            gis_common.res.init();
        }
        gis_common.res.setRqCell(rqCell);
    },
    /**
     * 资源res 销毁
     */
    resDestroy: function () {
        if (gis_common.res != null) {
            {
                gis_common.res.Destroy();
            }
            gis_common.res = null;
        }
    },
    /**
     * 测距
     */
    distanceLoad: function () {
        if (gis_common.distance == null) {
            gis_common.distance = new Distance();
            gis_common.distance.init();
        }
        gis_common.distance.start();
    },
    /**
     * 清理缓存
     */
    clearDataCache: function () {
        var r = confirm("清除缓存后，部分数据加载或图形渲染会变慢，你确定清理吗？")
        if (r == true) {
            $.ajax({
                url: "/cleardatacache",
                data: {},
                type: "GET",
                dataType: "json",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (req) {
                    gis_common.outPut(req, function (data) {
                        if (data == "true") {
                            gis_common.showMessage("清理成功");
                        }
                        else {
                            gis_common.showMessage("清理失败");
                        }
                    });
                },
                complete: function () {
                    gis_common.isLoadingSunCount();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        }
    },

    createCellScene: function (obj) {
        if (gis_common.scene == null) {
            gis_common.scene = new Scene();
            gis_common.scene.init();
        }
        gis_layout.createToolbarWithFun("cell_scene_div", obj, 320, gis_common.scene.createSceneHolderDiv);
    },
    /**
     * 地图图层
     */
    layerIdList: {
        markLayer: {
            id: 'markLayer',
            index: 1000,
            name: '标记'
        },
        cellLayer: {
            id: 'cellLayer',
            index: 11,
            name: '小区'
        },
        poiLayer: {
            id: 'poiLayer',
            index: 12,
            name: 'POI'
        },
        btsLayer: {
            id: 'btsLayer',
            index: 13,
            name: '2G'
        },
        tdLayer: {
            id: 'tdLayer',
            index: 14,
            name: '3G'
        },
        lteLayer: {
            id: 'lteLayer',
            index: 15,
            name: '4G'
        }
    }
};

/**
 * 通用资源  缓存数据  公共数据获取
 */
var gis_resources = {
    dataCache: new KeyValues(), //临时缓存数据
    /**
     * 添加缓存 如果KEY 相同  则覆盖以前的
     * @param key 缓存关键字
     * @param data  数据
     */
    addCache: function (key, data) {
        if (gis_resources.dataCache.containsKey(key)) {
            gis_resources.dataCache.removeKey(key);
        }
        gis_resources.dataCache.setAt(key, data);
    },
    /**
     * 移除缓存
     * @param key
     */
    removerCache: function (key) {
        gis_resources.dataCache.removeKey(key);
    },
    /**
     * 获取缓存
     * @param key
     * @returns {已缓存的对象}
     */
    getCache: function (key) {
        var data = null;
        if (gis_resources.dataCache.containsKey(key)) {
            data = gis_resources.dataCache.lookUp(key);
        }
        return data;
    },
    /**
     * 获取地市数据
     * @param callback 回调方法
     */
    getRegions: function (callback) {
        var key = "gis_resources_regions";
        var data = gis_resources.getCache(key);
        if (data == null || data == undefined) {
            $.ajax({
                url: "/getregions",
                dataType: "json",
                async: true,
                type: "GET",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (r) {
                    gis_common.outPut(r, function (d) {
                        data = d;
                        gis_resources.addCache(key, data);
                        callback(data);
                    });
                },
                complete: function () {
                    gis_common.isLoadingSunCount();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.showError("获取地市信息出错：" + XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        }
        else {
            return callback(data);
        }
    }
};

/** 通用功能 坐标系转换
 WGS-84：是国际标准，GPS坐标（Google Earth使用、或者GPS模块）
 GCJ-02：中国坐标偏移标准，Google Map、高德、腾讯使用
 BD-09：百度坐标偏移标准，Baidu Map使用
 //WGS-84 to GCJ-02
 GPS.gcj_encrypt();
 //GCJ-02 to WGS-84 粗略
 GPS.gcj_decrypt();
 //GCJ-02 to WGS-84 精确(二分极限法)
 // var threshold = 0.000000001; 目前设置的是精确到小数点后9位，这个值越小，越精确，但是javascript中，浮点运算本身就不太精确，九位在GPS里也偏差不大了
 GSP.gcj_decrypt_exact();
 //GCJ-02 to BD-09
 GPS.bd_encrypt();
 //BD-09 to GCJ-02
 GPS.bd_decrypt();
 //求距离
 GPS.distance();
 */
var GPS = {
    PI: 3.14159265358979324,
    x_pi: 3.14159265358979324 * 3000.0 / 180.0,
    delta: function (lat, lon) {
        // Krasovsky 1940
        //
        // a = 6378245.0, 1/f = 298.3
        // b = a * (1 - f)
        // ee = (a^2 - b^2) / a^2;
        var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
        var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
        var dLat = this.transformLat(lon - 105.0, lat - 35.0);
        var dLon = this.transformLon(lon - 105.0, lat - 35.0);
        var radLat = lat / 180.0 * this.PI;
        var magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        var sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
        return {
            'lat': dLat,
            'lon': dLon
        };
    },

    /**
     * WGS-84 to GCJ-02
     * @param wgsLat 纬度
     * @param wgsLon 经度
     * @returns {{lat: *, lon: *}}
     */
    gcj_encrypt: function (wgsLat, wgsLon) {
        if (this.outOfChina(wgsLat, wgsLon))
            return {
                'lat': wgsLat,
                'lon': wgsLon
            };

        var d = this.delta(wgsLat, wgsLon);
        return {
            'lat': wgsLat + d.lat,
            'lon': wgsLon + d.lon
        };
    },
    /**
     * GCJ-02 to WGS-84
     * @param gcjLat 纬度
     * @param gcjLon 经度
     * @returns  {{lat: *, lon: *}}
     */
    gcj_decrypt: function (gcjLat, gcjLon) {
        if (this.outOfChina(gcjLat, gcjLon))
            return {
                'lat': gcjLat,
                'lon': gcjLon
            };

        var d = this.delta(gcjLat, gcjLon);
        return {
            'lat': gcjLat - d.lat,
            'lon': gcjLon - d.lon
        };
    },
    /**
     * GCJ-02 to WGS-84 exactly
     * @param gcjLat 纬度
     * @param gcjLon 经度
     * @returns {{lat: *, lon: *}}
     */
    gcj_decrypt_exact: function (gcjLat, gcjLon) {
        var initDelta = 0.01;
        var threshold = 0.000000001;
        var dLat = initDelta,
            dLon = initDelta;
        var mLat = gcjLat - dLat,
            mLon = gcjLon - dLon;
        var pLat = gcjLat + dLat,
            pLon = gcjLon + dLon;
        var wgsLat,
            wgsLon,
            i = 0;
        while (1) {
            wgsLat = (mLat + pLat) / 2;
            wgsLon = (mLon + pLon) / 2;
            var tmp = this.gcj_encrypt(wgsLat, wgsLon)
            dLat = tmp.lat - gcjLat;
            dLon = tmp.lon - gcjLon;
            if ((Math.abs(dLat) < threshold) && (Math.abs(dLon) < threshold))
                break;

            if (dLat > 0)
                pLat = wgsLat;
            else
                mLat = wgsLat;
            if (dLon > 0)
                pLon = wgsLon;
            else
                mLon = wgsLon;

            if (++i > 10000)
                break;
        }
        //console.log(i);
        return {
            'lat': wgsLat,
            'lon': wgsLon
        };
    },
    /**
     * GCJ-02 to BD-09
     * @param gcjLat 纬度
     * @param gcjLon 经度
     * @returns {{lat: (number|*), lon: (number|*)}}
     */
    bd_encrypt: function (gcjLat, gcjLon) {
        var x = gcjLon,
            y = gcjLat;
        var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * this.x_pi);
        var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * this.x_pi);
        bdLon = z * Math.cos(theta) + 0.0065;
        bdLat = z * Math.sin(theta) + 0.006;
        return {
            'lat': bdLat,
            'lon': bdLon
        };
    },
    /**
     * BD-09 to GCJ-02
     * @param bdLat 纬度
     * @param bdLon 经度
     * @returns {{lat: number, lon: number}}
     */
    bd_decrypt: function (bdLat, bdLon) {
        var x = bdLon - 0.0065,
            y = bdLat - 0.006;
        var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * this.x_pi);
        var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * this.x_pi);
        var gcjLon = z * Math.cos(theta);
        var gcjLat = z * Math.sin(theta);
        return {
            'lat': gcjLat,
            'lon': gcjLon
        };
    },
    /**
     * WGS-84 to Web mercator mercatorLat -> y mercatorLon -> x
     * @param wgsLat
     * @param wgsLon
     * @returns {{lat: number, lon: number}}
     */
    mercator_encrypt: function (wgsLat, wgsLon) {
        var x = wgsLon * 20037508.34 / 180.0;
        var y = Math.log(Math.tan((90.0 + wgsLat) * this.PI / 360.0)) / (this.PI / 180.0);
        y = y * 20037508.34 / 180.0;
        return {
            'lat': y,
            'lon': x
        };
        /*
         if ((Math.abs(wgsLon) > 180 || Math.abs(wgsLat) > 90))
         return null;
         var x = 6378137.0 * wgsLon * 0.017453292519943295;
         var a = wgsLat * 0.017453292519943295;
         var y = 3189068.5 * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)));
         return {'lat' : y, 'lon' : x};
         //*/
    },
    /**
     * Web mercator to WGS-84 mercatorLat -> y mercatorLon -> x
     * @param mercatorLat
     * @param mercatorLon
     * @returns {{lat: number, lon: number}}
     */
    mercator_decrypt: function (mercatorLat, mercatorLon) {
        var x = mercatorLon / 20037508.34 * 180.;
        var y = mercatorLat / 20037508.34 * 180.;
        y = 180 / this.PI * (2 * Math.atan(Math.exp(y * this.PI / 180.)) - this.PI / 2);
        return {
            'lat': y,
            'lon': x
        };
        /*
         if (Math.abs(mercatorLon) < 180 && Math.abs(mercatorLat) < 90)
         return null;
         if ((Math.abs(mercatorLon) > 20037508.3427892) || (Math.abs(mercatorLat) > 20037508.3427892))
         return null;
         var a = mercatorLon / 6378137.0 * 57.295779513082323;
         var x = a - (Math.floor(((a + 180.0) / 360.0)) * 360.0);
         var y = (1.5707963267948966 - (2.0 * Math.atan(Math.exp((-1.0 * mercatorLat) / 6378137.0)))) * 57.295779513082323;
         return {'lat' : y, 'lon' : x};
         //*/
    },
    /**
     * two point's distance 两点间的距离
     * @param latA
     * @param lonA
     * @param latB
     * @param lonB
     * @returns {number}
     */
    distance: function (latA, lonA, latB, lonB) {
        var earthR = 6371000.;
        var x = Math.cos(latA * this.PI / 180.) * Math.cos(latB * this.PI / 180.) * Math.cos((lonA - lonB) * this.PI / 180);
        var y = Math.sin(latA * this.PI / 180.) * Math.sin(latB * this.PI / 180.);
        var s = x + y;
        if (s > 1)
            s = 1;
        if (s < -1)
            s = -1;
        var alpha = Math.acos(s);
        var distance = alpha * earthR;
        return distance;
    },
    outOfChina: function (lat, lon) {
        if (lon < 72.004 || lon > 137.8347)
            return true;
        if (lat < 0.8293 || lat > 55.8271)
            return true;
        return false;
    },
    transformLat: function (x, y) {
        var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    },
    transformLon: function (x, y) {
        var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
        return ret;
    }
};

/** 通用查询功能
 */
function CommonQuery() {
    var mark_layer = gis_core.getLayer(gis_common.layerIdList.markLayer.id);
    var map_click_handle = null;
    var poiCount = 0;
    var callbackCount = 0;
    var toolbar = null;
    var tempDrawLayer = null; //gis_core.addGraphicsLayerWithIndex('cell_scene_draw_layer', '区域框选', 2);
    var ringType = "";
    var isDrawing = false;
    // 继承 ResValue类
    var showDetail = function (resvalues) {
        callbackCount = callbackCount + 1;
        var content = "";
        if (resvalues != null && resvalues != undefined && resvalues.length > 0) {
            poiCount = poiCount + resvalues.length;

            $("#commonquery_content").show();

            for (var i = 0; i < resvalues.length; i++) {
                var rs = resvalues[i];
                content += "<li onClick='gis_common.commonQuery.setLocation(" + rs.longitude + "," + rs.latitude + ",\"" + rs.name + "\");'>";
                content += "<div class='result-title'><i class='fa fa-location-arrow'/>" + rs.name + "</div>";
                if (rs.hasOwnProperty("addr")) {
                    content += "<div class='result-detail' >" + rs.regionName + " " + rs.addr + "</div>";
                } else {
                }
                content += "</li>";
            }
            $(".search-cont-list").append(content);
        } else {
            $("#commonquery_content").hide();
        }

        if (callbackCount == gis_common.queryFunList.getCount() && poiCount == 0) {
            var q = $(".srh-inp").val();
            if (gis_common.poi == null) {
                gis_common.poi = new Poi();
            }
            gis_common.poi.onlyQuery(q, showDetail);
        }
    };
    //定位
    this.setLocation = function (longitude, latitude, name) {
        mark_layer.clear();

        var spatialReference = new esri.SpatialReference({wkid: gis_core.initconfig.wkid});
        var point = new esri.geometry.Point(longitude, latitude, spatialReference);
        var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 28, 28);
        //var symbol = new esri.symbol.PictureMarkerSymbol('/images/start.gif', 28, 28);
        var graphic = new esri.Graphic(point, symbol);
        mark_layer.add(graphic);

        var textSymbol = new esri.symbol.TextSymbol(name);
        textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_MIDDLE);
        textSymbol.setOffset(5, 14);
        textSymbol.setFont(new esri.symbol.Font("16pt"));
        textSymbol.setFont(esri.symbol.Font.WEIGHT_BOLD);
        var textgraphic = new esri.Graphic(point, textSymbol);

        mark_layer.add(textgraphic);

        var level = gis_core.map.getMaxZoom() - 2;
        if (gis_core.map.spatialReference.wkid == 102100) {
            var temp = GPS.mercator_encrypt(latitude, longitude);
            var p = new esri.geometry.Point(temp.lon, temp.lat, gis_core.map.spatialReference);
            gis_core.map.centerAndZoom(p, level);
        } else {
            gis_core.map.centerAndZoom(point, level);
        }
    };

    var extentchange = function (delta) {
        var a = delta;
    };

    var onDrawEnd = function (event) {
        var r = "";
        if (ringType == "1") {
            /*var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 28, 28);
             var graphic = new esri.Graphic(event.geometry, symbol);
             tempDrawLayer.add(graphic);*/
            if (event.geometry.spatialReference.wkid == 102100) {
                var p = GPS.mercator_decrypt(event.geometry.y, event.geometry.x);
                r = p.lon.toFixed(6) + "," + p.lat.toFixed(6);
            }
            else {
                r = event.geometry.x.toFixed(6) + "," + event.geometry.y.toFixed(6);
            }
        }
        else if (ringType == "2") {
            var rings = event.geometry.rings[0];
            var symbol = new esri.symbol.SimpleFillSymbol().setColor(new esri.Color([180, 168, 192, 0.5])).setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 0, 0]), 2));
            var graphic = new esri.Graphic(event.geometry, symbol);
            tempDrawLayer.add(graphic);

            for (var i = 0; i < rings.length; i++) {
                if (event.geometry.spatialReference.wkid == 102100) {
                    var p = GPS.mercator_decrypt(rings[i][1], rings[i][0]);
                    r += p.lon.toFixed(6) + "," + p.lat.toFixed(6) + ";";
                }
                else {
                    r += rings[i][0].toFixed(6) + "," + rings[i][1].toFixed(6) + ";";
                }
            }
        }
        if (ringType == "3") {
            var sls = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 0, 0]), 2);
            var graphic = new esri.Graphic(event.geometry, sls);
            tempDrawLayer.add(graphic);

            var paths = event.geometry.paths[0];
            for (var i = 0; i < paths.length; i++) {
                if (event.geometry.spatialReference.wkid == 102100) {
                    var p = GPS.mercator_decrypt(paths[i][1], paths[i][0]);
                    r += p.lon.toFixed(6) + "," + p.lat.toFixed(6) + ";";
                }
                else {
                    r += paths[i][0].toFixed(6) + "," + paths[i][1].toFixed(6) + ";";
                }
            }
        }
        //弹框
        toolbar.deactivate();
        $("#commonquery_show_text").val(r);
        gis_core.map.setMapCursor("default");
        gis_core.isEnableMapClick = true;
        isDrawing = false;
    };

    var addPoint = function (point) {
        //加点
        var outSymbol = new esri.symbol.SimpleLineSymbol();
        outSymbol.setStyle(esri.symbol.SimpleLineSymbol.STYLE_NULL);
        var symbolred = new esri.symbol.SimpleMarkerSymbol();
        symbolred.setOutline(outSymbol);
        symbolred.setSize(9);
        symbolred.setColor(new esri.Color([255, 0, 0, 1]));
        var graphic = new esri.Graphic(point, symbolred);
        tempDrawLayer.add(graphic);
        //显示距离
        var text = "";
        if (point.spatialReference.wkid == 102100) {
            var p = GPS.mercator_decrypt(point.y, point.x);
            text = p.lon.toFixed(6) + "," + p.lat.toFixed(6);
        }
        else {
            text = point.x.toFixed(6) + "," + point.y.toFixed(6);
        }

        var textSymbol = new esri.symbol.TextSymbol(text);
        textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_START);
        textSymbol.setColor(new esri.Color([255, 0, 0, 1]));
        textSymbol.setOffset(10, -3);
        textSymbol.setFont(new esri.symbol.Font("12pt"));
        var textgraphic = new esri.Graphic(point, textSymbol);
        tempDrawLayer.add(textgraphic);
    }

    function undocument(c, d) {
        $(document).unbind('click');
        $(document).bind('click', function (e) {
            if (!$(".modal-search").is($(e.target)) && !$(".srh-inp").is($(e.target)) &&
                $(".modal-search").has($(e.target)).length == 0 && !$(".srh-r").is($(e.target)) &&
                $(".srh-r").has($(e.target)).length == 0) {
                $(c).hide(400);
                $(d).fadeIn(200);
            }
        });
    }

    this.setPoint = function (lon, lat) {
        mark_layer.clear();
        var spatialReference = new esri.SpatialReference({wkid: gis_core.initconfig.wkid});
        var point = new esri.geometry.Point(lon, lat, spatialReference);
        var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 28, 28);
        var graphic = new esri.Graphic(point, symbol);
        mark_layer.add(graphic);
        gis_common.setExtent(parseFloat(lon) + 0.002, parseFloat(lat) + 0.002, parseFloat(lon) - 0.002, parseFloat(lat) - 0.002);
    };

    this.showPointHtml = function (callback) {
        var content = "<div class='form-group'>";
        content += "	<label class='col-sm-3 control-label'>经纬度:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "		<input id='commonquery_show_text' type='text' class='form-control' placeholder='经度,纬度;经度,纬度;....'>";
        content += "	</div>";
        content += "</div>";
        content += "<div class='form-group'>";
        content += " 	<div class='col-sm-9 col-sm-offset-3'>";
        content += "		<button id='commonquery_show_btn' class='btn btn-primary'>定 位</button>";
        content += "		<button id='commonquery_clear_btn' class='btn btn-primary'>清 理</button>";
        content += "	</div>";
        content += "</div>";
        content += "<div class='form-group'>";
        content += "	<label class='col-sm-3 control-label'>获取坐标:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "         <button type='button' class='list-group-item _point_btn'><i class='fa fa-square-o'></i> 点";
        content += "         </button>";
        content += "         <button type='button' class='list-group-item _polygon_btn'><i class='fa fa-star-o'></i> 不规则区域";
        content += "         </button>";
        content += "          <button type='button' class='list-group-item _line_btn'><i class='fa fa-line-chart'></i> 直线";
        content += "          </button>";
        content += "	</div>";
        content += "</div>";
        var div = $(content);
        div.find("#commonquery_show_btn").bind("click", function () {
            mark_layer.clear();
            var txt = div.find("#commonquery_show_text").val();
            txt = txt.replace(new RegExp("，", 'g'), ',').replace(new RegExp("；", 'g'), ';');
            var txtarr = txt.split(";")
            var spatialReference = new esri.SpatialReference({wkid: gis_core.initconfig.wkid});
            var xmax = 0, xmin = 0, ymax = 0, ymin = 0;
            for (var i = 0; i < txtarr.length; i++) {
                if (gis_common.stringIsNullOrWhiteSpace(txtarr[i])) {
                    continue;
                }

                var lon = parseFloat(txtarr[i].split(",")[0]);
                var lat = parseFloat(txtarr[i].split(",")[1]);
                var point = new esri.geometry.Point(lon, lat, spatialReference);
                var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 28, 28);
                var graphic = new esri.Graphic(point, symbol);
                mark_layer.add(graphic);
                if (xmax == 0) {
                    xmax = lon;
                    xmin = lon;
                    ymax = lat;
                    ymin = lat;
                }
                else {
                    xmax = lon > xmax ? lon : xmax;
                    xmin = lon < xmin ? lon : xmin;
                    ymax = lat > ymax ? lat : ymax;
                    ymin = lat < ymin ? lat : ymin;
                }
            }
            //if (xmax > 0)
            {
                gis_common.setExtent(parseFloat(xmax) + 0.005, parseFloat(ymax) + 0.005, parseFloat(xmin) - 0.005, parseFloat(ymin) - 0.005);
            }
        });

        div.find("#commonquery_clear_btn").click(function () {
            mark_layer.clear();
            if (tempDrawLayer != null) {
                tempDrawLayer.clear();
            }
        });

        div.find('._point_btn').on('click', function () {
            isDrawing = true;
            if (tempDrawLayer) {
                tempDrawLayer.clear()
            }
            gis_core.isEnableMapClick = false;
            gis_core.map.setMapCursor("url(/images/ruler.png),auto");
            toolbar.activate(esri.toolbars.Draw.POINT);
            ringType = 1;

        });
        div.find('._polygon_btn').on('click', function () {
            isDrawing = true;
            if (tempDrawLayer) {
                tempDrawLayer.clear()
            }
            gis_core.isEnableMapClick = false;
            gis_core.map.setMapCursor("url(/images/ruler.png),auto");
            toolbar.activate(esri.toolbars.Draw.POLYGON);
            ringType = 2;
        });
        div.find('._line_btn').on('click', function () {
            isDrawing = true;
            if (tempDrawLayer) {
                tempDrawLayer.clear()
            }
            gis_core.isEnableMapClick = false;
            gis_core.map.setMapCursor("url(/images/ruler.png),auto");
            toolbar.activate(esri.toolbars.Draw.POLYLINE);
            ringType = 3;
        });

        callback(div);
    };
    //查询
    this.query = function () {
        mark_layer.clear();
        var q = $(".srh-inp").val();
        if (gis_common.stringIsNullOrWhiteSpace(q)) {
            $(".srh-inp").focus();
            return;
        }
        $(".search-cont-list").html("");
        $(".hide-search").hide();
        $(".search-cont-list").show();
        poiCount = 0;
        callbackCount = 0;
        if (gis_common.queryFunList.getCount() > 0) {
            for (var i = 0; i < gis_common.queryFunList.getCount(); i++) {
                var fun = gis_common.queryFunList.values[i].value;
                fun(q, showDetail);
            }
        } else {
            if (gis_common.poi == null) {
                gis_common.poi = new Poi();
            }
            gis_common.poi.onlyQuery(q, showDetail);
        }
    };
    //初始化  注册事件
    this.init = function () {
        $(".srh-inp").unbind("keyup");
        //绑定回车事件
        $(".srh-inp").bind('keyup', function (event) {
            event = document.all ? window.event : event;
            if ((event.keyCode || event.which) == 13) {
                gis_common.query();
            }
        });

        $("#commonquery_content").hide();
        //关闭搜索面板
        undocument('.search-cont-list', '.hide-search');
        //显示搜索面板
        $('.hide-search').hover(function () {
            $('.search-cont-list').show(400);
            $('.search-close').show();
            $('.hide-search').fadeOut(200);
        });

        if (map_click_handle != null) {
            dojo.disconnect(map_click_handle);
        }
        map_click_handle = gis_core.map.on("click", function (evt) {
            if (isDrawing) {
                addPoint(evt.mapPoint);
            }
        });

        dojo.require("esri.toolbars.draw");
        tempDrawLayer = gis_core.addGraphicsLayerWithIndex('cell_scene_draw_layer', '区域框选', 2);
        toolbar = new esri.toolbars.Draw(gis_core.map, {
            tooltipOffset: 20,
            drawTime: 90,
            showTooltips: true
        });
        toolbar.on("draw-end", onDrawEnd);
    };
    //销毁
    this.destroy = function () {
        $(".srh-inp").unbind("keyup");
        mark_layer.clear();
        gis_common.commonQuery = null;
    };
    //模块信息
    this.title = {
        id: "00_00_03",
        name: "功能查询"
    };
};

/** POI查询
 */
function Poi() {
    //变量
    var poi_layer = gis_core.getLayer(gis_common.layerIdList.poiLayer.id);
    var poi_layer_ExtentChange_handle = null;
    var poi_layer_onMouseOver_handle = null;
    var poi_layer_onMouseOut_handle = null;
    var poi_layer_onClick_handle = null;
    var option = {};

    var extentchange = function (delta) {
        laodData();
    };

    var laodData = function () {
        gis_core.getLayer(gis_common.layerIdList.poiLayer.id).clear();
        $.ajax({
            url: "/getpois",
            data: {
                xmax: gis_core.map.extent.xmax,
                ymax: gis_core.map.extent.ymax,
                xmin: gis_core.map.extent.xmin,
                ymin: gis_core.map.extent.ymin,
                level: gis_core.map.getLevel()
            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                var pois = eval(req);
                showPoiPoint(pois);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var showPoiPoint = function (pois) {
        require(["esri/graphic", "esri/geometry/Point", "esri/symbols/PictureMarkerSymbol", "esri/symbols/TextSymbol", "dojo/domReady!"],
            function (Graphic, Point, PictureMarkerSymbol, TextSymbol) {
                for (var i = 0; i < pois.length; i++) {
                    var poi = pois[i];
                    var point = new Point(poi.longitude, poi.latitude, gis_core.map.spatialReference);
                    var attr = {
                        "poi": poi
                    };
                    if (poi.show == true) {
                        var symbol = new PictureMarkerSymbol('/images/poi.png', 10, 10);
                        var graphic = new Graphic(point, symbol, attr);
                        poi_layer.add(graphic);

                        var textSymbol = new TextSymbol(poi.name);
                        textSymbol.setAlign(TextSymbol.ALIGN_START);
                        textSymbol.setOffset(5, -5);
                        var textgraphic = new Graphic(point, textSymbol, attr);
                        poi_layer.add(textgraphic);
                    } else {
                        var symbol = new PictureMarkerSymbol('/images/poi.png', 5, 5);
                        var graphic = new Graphic(point, symbol, attr);
                        poi_layer.add(graphic);
                    }
                }
            });
    };

    var createMaxPoiGraphic = function (poi) {
        require(["esri/graphic", "esri/geometry/Point", "esri/symbols/PictureMarkerSymbol", "esri/symbols/TextSymbol", "dojo/domReady!"],
            function (Graphic, Point, PictureMarkerSymbol, TextSymbol) {
                var point = new Point(poi.longitude, poi.latitude, gis_core.map.spatialReference);
                var attr = {
                    "poi": poi
                };

                var textSymbol = new TextSymbol(poi.name);
                textSymbol.setAlign(TextSymbol.ALIGN_START);
                textSymbol.setOffset(5, -5);
                var textgraphic = new Graphic(point, textSymbol, attr);
                poi_layer.add(textgraphic);

                var attr_text = {
                    "poi": poi,
                    "text": textgraphic
                };
                var symbol = new PictureMarkerSymbol('/images/poi.png', 10, 10);
                var graphic = new Graphic(point, symbol, attr_text);

                poi_layer.add(graphic);
            });
    };

    var query = function (keywords, callback) {
        $.ajax({
            url: "/getpoistopn",
            data: {
                key: keywords,
                topn: 10
            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                var resvalues = eval(req);
                callback(resvalues);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    /**
     * 创建poi兴趣点分类列表
     * */
    var createPoiCategoryHtml = function (callback) {
        var html = [];
        html.push('<div class="" id="_poi_category_list">');
        /* html.push('    <div class=""><label><input type="checkbox" value=""> Option four disabled </label></div>');*/
        html.push('</div>');
        //加载poi category
        var $div = $(html.join(''));
        callback($div);
        loadCategoryList();
    };

    //加载poi点分类信息
    var loadCategoryList = function () {
        $.ajax({
            url: "/getpoicategory",
            data: {},
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (data) {
                addPoiCategoryList(data);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var addPoiCategoryList = function (data) {

        //{id: "233", level_f_id: "I", level_f_name: "生活服务", level_s_id: "I40", level_s_name: "家政服务"}
        if (data && data.length > 0) {
            var $list = $('#_poi_category_list');
            for (var i = 0, len = data.length; i < len; i++) {
                var $div = $('._category_item_' + data[i]['level_f_id']);
                if ($div.length == 0) {
                    $div = $('<div></div>').appendTo($list)
                        .addClass('category-item _category_item_' + data[i]['level_f_id'])
                        .append('<label><input type="checkbox" class="_category_item _category_' + data[i]['level_f_id'] + '" level="1" fid="' + data[i]['level_f_id'] + '" category_name="' + data[i]['level_f_name'] + '"> ' + data[i]['level_f_name'] + '</label>');
                    var $subList = $('<div class="category-item-sub-list _category_item_sub_list_' + data[i]['level_f_id'] + '"></div>');
                    $subList.appendTo($div);
                    var $subDiv = $('<div></div>');
                    $subDiv.appendTo($subList).addClass('category-item-sub')
                        .append('<label><input type="checkbox" class="_category_item _category_' + data[i]['level_s_id'] + '" level="2" fid="' + data[i]['level_f_id'] + '" sid="' + data[i]['level_s_id'] + '" category_name="' + data[i]['level_s_name'] + '"> ' + data[i]['level_s_name'] + '</label>');
                } else {
                    $subList = $('._category_item_sub_list_' + data[i]['level_f_id']);
                    $subDiv = $('<div></div>');
                    $subDiv.appendTo($subList).addClass('category-item-sub')
                        .append('<label><input type="checkbox" class="_category_item _category_' + data[i]['level_s_id'] + '" level="2" fid="' + data[i]['level_f_id'] + '" sid="' + data[i]['level_s_id'] + '" category_name="' + data[i]['level_s_name'] + '"> ' + data[i]['level_s_name'] + '</label>');
                }
            }
            var $btn = $('<button id="_query_poi_kpi" class="btn btn-primary">确 定</button>');
            $list.append($btn);
            $btn.click(function () {
                $('a[divid="_poi_category_holder"]').click();
                if (option.poiCateBtnClick && $.isFunction(option.poiCateBtnClick)) {
                    option.poiCateBtnClick();
                }
            });


            $('._category_item').click(function () {
                var level = $(this).attr('level');
                var fid = $(this).attr('fid');
                if (level == 1) {
                    if (this.checked) {
                        $('._category_item[level="2"][fid="' + fid + '"]').each(function () {
                            this.checked = true;
                        });
                    } else {
                        $('._category_item[level="2"][fid="' + fid + '"]').each(function () {
                            this.checked = false;
                        });
                    }
                } else {

                }

            });

        }
    };

    this.onlyQuery = function (keywords, callback) {
        query(keywords, callback);
    };

    this.init = function (pin) {
        option = $.extend(true, {
            obj: null,
            showCate: false,
            poiCateBtnClick: null
        }, pin);

        gis_core.addPlugin(this);
        laodData();
        gis_core.addExtentChange('poi_ExtentChange', extentchange);
        //gis_common.queryRegisterFun("poi", query);

        if (poi_layer_onMouseOver_handle != null) {
            dojo.disconnect(poi_layer_onMouseOver_handle);
        }
        //鼠标事件
        poi_layer_onMouseOver_handle = poi_layer.on("mouse-over", function (e) {
            var poi = e.graphic.attributes["poi"];
            if (poi.show == false) {
                require(["esri/graphic", "esri/geometry/Point", "esri/symbols/PictureMarkerSymbol", "esri/symbols/TextSymbol", "dojo/domReady!"],
                    function (Graphic, Point, PictureMarkerSymbol, TextSymbol) {
                        var poi = e.graphic.attributes["poi"];

                        var point = new Point(poi.longitude, poi.latitude, gis_core.map.spatialReference);
                        var textSymbol = new TextSymbol(poi.name);
                        textSymbol.setAlign(TextSymbol.ALIGN_START);
                        textSymbol.setOffset(5, -5);
                        var textgraphic = new Graphic(point, textSymbol);
                        poi_layer.add(textgraphic);

                        var attr = {
                            "poi": poi,
                            "text": textgraphic
                        };

                        e.graphic.attributes = attr;
                        var symbol = new PictureMarkerSymbol('/images/poi.png', 10, 10);
                        e.graphic.setSymbol(symbol);

                    });
            }
        });

        if (poi_layer_onMouseOut_handle != null) {
            dojo.disconnect(poi_layer_onMouseOut_handle);
        }
        //鼠标移开事件
        poi_layer_onMouseOut_handle = poi_layer.on("mouse-out", function (e) {
            if (e.graphic.attributes != undefined && e.graphic.attributes["text"] != undefined) {
                var textgraphic = e.graphic.attributes["text"];
                poi_layer.remove(textgraphic);
                var symbol = new esri.symbol.PictureMarkerSymbol('/images/poi.png', 5, 5);
                e.graphic.setSymbol(symbol);
            }
        });

        if (option.showCate) {
            gis_layout.createToolbarWithFun("_poi_category_holder", option.obj, 194, createPoiCategoryHtml);
        }

    };

    this.destroy = function () {
        if (poi_layer_onMouseOver_handle != null) {
            dojo.disconnect(poi_layer_onMouseOver_handle);
        }

        if (poi_layer_onMouseOut_handle != null) {
            dojo.disconnect(poi_layer_onMouseOut_handle);
        }

        if (poi_layer_onClick_handle != null) {
            dojo.disconnect(poi_layer_onClick_handle);
        }
        gis_core.removeExtentChange("poi_ExtentChange");
        poi_layer.clear();
        gis_common.poi = null;
    };

    //模块信息
    this.title = {
        id: "00_00_02",
        name: "POI信息"
    };
}

/**
 * 测距
 * @constructor
 */
function Distance() {
    var lineLayer = null;//gis_core.addGraphicsLayer("distance_linelayer", "测距图层");
    var map_click_handle = null;
    var lineLayer_click_handle = null;
    var tb = null;
    var isDistance = false;
    var lon = 0;
    var lat = 0;
    var d = 0;

    function initToolbar() {
        isDistance = true;
        gis_core.isEnableMapClick = false;
        gis_core.map.setMapCursor("url(/images/ruler.png),auto");
        gis_core.map.attr("isdistanceisdistanceisdistanceisdistanceisdistanceisdistanceisdistance", true);

        lon = 0;
        lat = 0;
        d = 0;
        tb = new esri.toolbars.draw(gis_core.map);
        tb.on("draw-end", drawEnd);
        tb.on("draw-complete", drawComplete);
        gis_core.map.disableMapNavigation();
        tb.activate("polyline");
    }

    function drawEnd(evt) {
        tb.deactivate();
        gis_core.map.enableMapNavigation();
        var symbol = new esri.symbol.CartographicLineSymbol(
            esri.symbol.CartographicLineSymbol.STYLE_SOLID,
            new esri.Color([255, 0, 0]), 3,
            esri.symbol.CartographicLineSymbol.CAP_ROUND,
            esri.symbol.CartographicLineSymbol.JOIN_MITER);
        lineLayer.add(new esri.Graphic(evt.geometry, symbol));
    }

    function drawComplete(evt) {
        isDistance = false;
        gis_core.map.setMapCursor("default");
        var attr = {
            "data": "end"
        };
        var point = new esri.geometry.Point(lon, lat, gis_core.map.spatialReference);
        var symbol = new esri.symbol.PictureMarkerSymbol('/images/close.png', 16, 16);
        var graphic = new esri.Graphic(point, symbol, attr);
        lineLayer.add(graphic);

        gis_core.isEnableMapClick = true;
        if (map_click_handle != null) {
            dojo.disconnect(map_click_handle);
            map_click_handle = null;
        }
    }

    function addDisText(lon, lat, dis) {
        var point = new esri.geometry.Point(lon, lat, gis_core.map.spatialReference);
        var text = dis + "m";
        if (dis == 0) {
            text = "起点";
        }
        else if (dis >= 1000) {
            text = (dis / 1000).toFixed(2) + "km"
        }
        else {
            text = dis.toFixed(2) + "m";
        }
        //加点
        var outSymbol = new esri.symbol.SimpleLineSymbol();
        outSymbol.setStyle(esri.symbol.SimpleLineSymbol.STYLE_NULL);
        var symbolred = new esri.symbol.SimpleMarkerSymbol();
        symbolred.setOutline(outSymbol);
        symbolred.setSize(9);
        symbolred.setColor(new esri.Color([255, 0, 0, 1]));
        var graphic = new esri.Graphic(point, symbolred);
        lineLayer.add(graphic);
        //显示距离
        var textSymbol = new esri.symbol.TextSymbol(text);
        textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_START);
        textSymbol.setColor(new esri.Color([255, 0, 0, 1]));
        textSymbol.setOffset(10, -3);
        textSymbol.setFont(new esri.symbol.Font("12pt"));
        var textgraphic = new esri.Graphic(point, textSymbol);
        lineLayer.add(textgraphic);
    }

    this.start = function () {
        if (map_click_handle != null) {
            dojo.disconnect(map_click_handle);
        }
        map_click_handle = gis_core.map.on("click", function (evt) {
                var x = evt.mapPoint.x;
                var y = evt.mapPoint.y;
                if (isDistance == true) {
                    if (lon == 0 || lat == 0) {
                        lon = x;
                        lat = y;
                    }
                    else {
                        if (gis_core.map.spatialReference.wkid == 4326) {
                            d = d + GPS.distance(lat, lon, y, x);
                        }
                        else {
                            d = d + Math.sqrt((x - lon) * (x - lon) + (y - lat) * (y - lat));
                        }
                    }
                    addDisText(x, y, d);
                    lon = x;
                    lat = y;
                }
            }
        );

        if (lineLayer != null) {
            gis_core.removeLayer("distance_linelayer");
        }
        lineLayer = gis_core.addGraphicsLayer("distance_linelayer", "测距图层");
        if (lineLayer_click_handle != null) {
            dojo.disconnect(lineLayer_click_handle);
        }
        lineLayer_click_handle = lineLayer.on("click", function (evt) {
            if (evt.graphic.attributes != undefined) {
                var data = evt.graphic.attributes.data;
                lineLayer.clear();
            }
        });

        initToolbar();
    };

    this.init = function () {
        gis_core.addPlugin(this);
        dojo.require("esri.toolbars.draw");
    };

    this.destroy = function () {

    };

    //模块信息
    this.title = {
        id: "00_00_02",
        name: "测距"
    };
}

/** 资源（小区 基站）查询
 */
function Res() {
    //变量
    var btslayer = gis_core.getLayer(gis_common.layerIdList.btsLayer.id);
    var tdLayer = gis_core.getLayer(gis_common.layerIdList.tdLayer.id);
    var lteLayer = gis_core.getLayer(gis_common.layerIdList.lteLayer.id);
    var cellLayer = gis_core.getLayer(gis_common.layerIdList.cellLayer.id);
    var dialog = null;

    var lteLayer_onMouseOver_handle = null;
    var lteLayer_onMouseOut_handle = null;
    var lteLayer_onClick_handle = null;

    var tdLayer_onMouseOver_handle = null;
    var tdLayer_onMouseOut_handle = null;
    var tdLayer_onClick_handle = null;

    var btslayer_onMouseOver_handle = null;
    var btslayer_onMouseOut_handle = null;
    var btslayer_onClick_handle = null;

    var cellLayer_onMouseOver_handle = null;
    var cellLayer_onMouseOut_handle = null;
    var cellLayer_onClick_handle = null;

    //查询基站的条件
    var RqCell = {
        gsm: false,
        td: false,
        lte: false,
        alonecell: 0,
        region: {
            id: 1,
            type: 9000
        }
    };

    var extentchange = function (delta) {
        loadData();
    };

    var loadData = function () {
        btslayer.clear();
        tdLayer.clear();
        lteLayer.clear();
        cellLayer.clear();
        if (RqCell.gsm == false && RqCell.td == false && RqCell.lte == false) {
            return;
        }
        /*var extent = gis_common.getMapExtent();
        if (extent.wkid == 102100) {
            var pmax = GPS.mercator_decrypt(extent.yMax, extent.xMax);
            var pmin = GPS.mercator_decrypt(extent.yMin, extent.xMin);
            extent.xMax = pmax.lon;
            extent.yMax = pmax.lat;
            extent.xMin = pmin.lon;
            extent.yMin = pmin.lat;
            extent.wkid = 4326;
        }*/
        $.ajax({
            url: "/getbts",
            data: {
                extent: JSON.stringify(gis_common.getMapExtent()),
                rqcell: JSON.stringify(RqCell)
            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                btslayer.clear();
                tdLayer.clear();
                lteLayer.clear();
                cellLayer.clear();

                var bts = eval(req);
                showPoint(bts);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var showPoint = function (bts) {
        for (var i = 0, len = bts.length; i < len; i++) {
            var b = bts[i];
            var graphics = gis_common.createBtsGraphic(b);

            var layer = btslayer;
            if (b.tag == "cluster" || b.resType == "GSMCELL") {
                layer = btslayer;
            } else if (b.resType == "LTECELL") {
                layer = lteLayer;
            } else if (b.resType == "TDCELL") {
                layer = tdLayer
            }

            for (var j = 0, j_len = graphics.length; j < j_len; j++) {
                layer.add(graphics[j]);
            }
        }
    };

    var tooltip = function (evt) {
        if (evt.graphic.attributes.dialog != undefined && evt.graphic.attributes.dialog == true) {
            return;
        }
        if (evt.graphic.attributes.data.tag == "cluster") {
            return;
        }
        var t = "<b>" + evt.graphic.attributes.name + "</b>";
        dialog.setContent(t);
        dijit.popup.open({
            popup: dialog,
            x: evt.pageX,
            y: evt.pageY
        });
        evt.graphic.attributes.dialog = true;
    };

    var btsOnClick = function (evt) {
        cellLayer.clear();
        var bts = evt.graphic.attributes.data;
        if (evt.graphic.attributes.data.tag == "cluster") {
            return;
        }
        if (bts.cells != null) {
            for (var i = 0; i < bts.cells.length; i++) {
                var cell = bts.cells[i];
                var graphic = gis_common.createCellGraphic(cell);
                cellLayer.add(graphic);
            }
        }
    };

    var closeDialog = function (evt) {
        dijit.popup.close(dialog);
        evt.graphic.attributes.dialog = false;
    };

    var query = function (keywords, callback) {
        $.ajax({
            url: "/getbtstopn",
            data: {
                key: keywords,
                topn: 10,
                rqcell: JSON.stringify(RqCell)
            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                var resvalues = eval(req);
                callback(resvalues);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError("基站模糊查询出错：" + XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var createHtml = function (regions) {
        var content = "<div class='form-group'>";
        content += "	<label class='col-sm-3 control-label'>基站类型:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "		<div class='checkbox pull-left margin-right-20'>";
        content += "			<label> <input id='res_type_select_lte' type='checkbox' restype = 'lte'> 4G </label>";
        content += "		</div>";
        content += "		<div class='checkbox pull-left margin-right-20'>";
        content += "			<label> <input id='res_type_select_td' type='checkbox' restype = 'td'> 3G </label>";
        content += "		</div>";
        content += "		<div class='checkbox pull-left margin-right-20'>";
        content += "			<label><input id='res_type_select_gsm' type='checkbox' restype = 'gsm'> 2G </label>";
        content += "		</div>";
        content += "	</div>";
        content += "</div>";

        content += "<div class='form-group'>";
        content += "	<label for='' class='col-sm-3 control-label'>地市:</label>";
        content += " 	<div class='col-sm-9'>";
        content += "		<select id='res_region_select' class='form-control'>";
        if (regions != null && regions != undefined && regions.length > 0) {
            for (var i = 0; i < regions.length; i++) {
                var r = regions[i];
                content += "<option neid='" + r.id + "' netype='" + r.type + "'>" + r.name + "</option>";
            }
        } else {
            content += "<option neid='1' netype='9000'>全部</option>";
        }
        content += "		</select>";
        content += "	</div>";
        content += "</div>";

        content += "<div class='form-group'>";
        content += " 	<div class='col-sm-9 col-sm-offset-3'>";
        content += "		<button id='res_btn_load' class='btn btn-primary'>确 定</button>";
        content += "	</div>";
        content += "</div>";

        var div = $(content);
        div.find("#res_btn_load").bind("click", function (e) {
            //资源类型
            RqCell.lte = $("#res_type_select_lte")[0].checked;
            RqCell.td = $("#res_type_select_td")[0].checked;
            RqCell.gsm = $("#res_type_select_gsm")[0].checked;
            //地市
            var selects = $("#res_region_select option:selected");
            if (selects != null && selects != undefined) {
                RqCell.region.id = selects.attr("neid");
                RqCell.region.type = selects.attr("netype");
            }
            loadData();
            $('a[divid="res_param_div"]').click();
        });

        return div;
    };

    this.createParamDiv = function (callback) {
        gis_resources.getRegions(function (data) {
            var content = createHtml(data);
            callback(content);
        });
    };

    this.init = function () {
        gis_core.addPlugin(this);
        gis_core.addExtentChange('res_ExtentChange', extentchange);
        dialog = new dijit.TooltipDialog({
            id: "tooltipDialog",
            style: "position: absolute; width: auto; font: normal normal normal 10pt Helvetica;z-index:100"
        });
        dialog.startup();

        //鼠标事件
        //4G基站事件
        if (lteLayer_onMouseOver_handle != null) {
            dojo.disconnect(lteLayer_onMouseOver_handle);
        }
        lteLayer_onMouseOver_handle = lteLayer.on("mouse-over", tooltip);
        if (lteLayer_onMouseOut_handle != null) {
            dojo.disconnect(lteLayer_onMouseOut_handle);
        }
        lteLayer_onMouseOut_handle = lteLayer.on("mouse-out", closeDialog);
        if (lteLayer_onClick_handle != null) {
            dojo.disconnect(lteLayer_onClick_handle);
        }
        lteLayer_onClick_handle = lteLayer.on("click", function (evt) {
            btsOnClick(evt);
        });

        //3G基站事件
        if (tdLayer_onMouseOver_handle != null) {
            dojo.disconnect(tdLayer_onMouseOver_handle);
        }
        tdLayer_onMouseOver_handle = tdLayer.on("mouse-over", tooltip);
        if (tdLayer_onMouseOut_handle != null) {
            dojo.disconnect(tdLayer_onMouseOut_handle);
        }
        tdLayer_onMouseOut_handle = tdLayer.on("mouse-out", closeDialog);
        if (tdLayer_onClick_handle != null) {
            dojo.disconnect(tdLayer_onClick_handle);
        }
        tdLayer_onClick_handle = tdLayer.on("click", function (evt) {
            btsOnClick(evt);
        });

        //2G基站事件
        if (btslayer_onMouseOver_handle != null) {
            dojo.disconnect(btslayer_onMouseOver_handle);
        }
        btslayer_onMouseOver_handle = btslayer.on("mouse-over", tooltip);
        if (btslayer_onMouseOut_handle != null) {
            dojo.disconnect(btslayer_onMouseOut_handle);
        }
        btslayer_onMouseOut_handle = btslayer.on("mouse-out", closeDialog);
        if (btslayer_onClick_handle != null) {
            dojo.disconnect(btslayer_onClick_handle);
        }
        btslayer_onClick_handle = btslayer.on("click", function (evt) {
            btsOnClick(evt);
        });

        //小区事件
        if (cellLayer_onMouseOver_handle != null) {
            dojo.disconnect(cellLayer_onMouseOver_handle);
        }
        cellLayer_onMouseOver_handle = cellLayer.on("mouse-over", tooltip);
        if (cellLayer_onMouseOut_handle != null) {
            dojo.disconnect(cellLayer_onMouseOut_handle);
        }
        cellLayer_onMouseOut_handle = cellLayer.on("mouse-out", closeDialog);
        if (cellLayer_onClick_handle != null) {
            dojo.disconnect(cellLayer_onClick_handle);
        }
        cellLayer_onClick_handle = cellLayer.on("click", function (evt) {
            //btsOnClick(evt);
        });

        //注册查询事件
        gis_common.queryRegisterFun("res", query);
    };

    this.destroy = function () {
        gis_core.removeExtentChange("res_ExtentChange");
        //4G基站事件
        if (lteLayer_onMouseOver_handle != null) {
            dojo.disconnect(lteLayer_onMouseOver_handle);
        }
        if (lteLayer_onMouseOut_handle != null) {
            dojo.disconnect(lteLayer_onMouseOut_handle);
        }
        //3G基站事件
        if (tdLayer_onMouseOver_handle != null) {
            dojo.disconnect(tdLayer_onMouseOver_handle);
        }
        //2G基站事件
        if (btslayer_onMouseOver_handle != null) {
            dojo.disconnect(btslayer_onMouseOver_handle);
        }
        //清理图层信息
        btslayer.clear();
        tdLayer.clear();
        lteLayer.clear();
        cellLayer.clear();
        //销毁对象
        gis_common.res = null;
    };

    //模块信息
    this.title = {
        id: "00_00_01",
        name: "小区资源"
    };

    this.setRqCell = function (rqCell) {
        RqCell = rqCell;
    }
}

/**
 * 自定义场景
 * */
function Scene() {
    var toolbar = null;
    var rings = null;
    var ringType = null;
    var tempDrawLayer = null;
    var scene_type_list = null;
    var newSceneId = 0;
    var cells = null;
    var regions = null;
    var region = {
        id: 1,
        type: 9000,
        name: '全部'
    };//地市
    var scene_type_id = "0";
    var city_id = "0";

    //业务变量
    var select_AppTopics_id = null;
    var select_AppTopics_name = null;
    var select_region_id = null;

    var createSceneHolderHtml = function (callback) {
        var html = [];
        html.push('<div class="form-horizontal" id="_cell_scene_div">');
        html.push(' <div class="form-group"><label class="col-sm-3 control-label">工具:</label>');
        html.push('    <div class="col-sm-9">');
        html.push('     <div class="list-group">');
        html.push('         <button type="button" class="list-group-item _rectangle_btn"><i class="fa fa-square-o"></i> 矩形选择区域');
        html.push('         </button>');
        html.push('         <button type="button" class="list-group-item _polygon_btn"><i class="fa fa-star-o"></i> 不规则区域');
        html.push('         </button>');
        //html.push('         <button type="button" class="list-group-item _line_btn"><i class="fa fa-line-chart"></i> 直线');
        //html.push('         </button>');
        html.push('     </div>');
        html.push('    </div>');
        html.push(' </div>');
        html.push(' <div class="form-group"><label class="col-sm-3 control-label">应用专题:</label>');
        html.push('    <div class="col-sm-9">');
        html.push('         <select id="scene_query_scene_apptopics_select" class="form-control"></select>');
        html.push('    </div>');
        html.push(' </div>');
        html.push(' <div class="form-group"><label class="col-sm-3 control-label">分公司:</label>');
        html.push('    <div class="col-sm-9">');
        html.push('         <select id="scene_query_city_select" class="form-control"></select>');
        html.push('    </div>');
        html.push(' </div>');
        html.push(' <div class="form-group"><label class="col-sm-3 control-label">分类:</label>');
        html.push('    <div class="col-sm-9">');
        html.push('         <select class="form-control _scene_type"></select>');
        html.push('    </div>');
        html.push(' </div>');
        html.push(' <div class="form-group"><label class="col-sm-3 control-label">场景:</label>');
        html.push('    <div class="col-sm-9">');
        html.push('     <div class="_cell_scene_list list-group" style="margin-bottom: 0;min-width:200px;max-height:175px;overflow-y:auto;"></div>');
        html.push('    </div>');
        html.push(' </div>');
        html.push(' <div class="form-group"><label class="col-sm-3 control-label"></label>');
        html.push('    <div class="col-sm-9">');
        //html.push('         <button id="_query_kpi" class="btn btn-primary">查    询</button>');
        html.push('         <button id="scene_cells_export" class="btn btn-primary">导出场景</button>');
        html.push('         <button id="scene_cells_inport" class="btn btn-primary">导入场景</button>');
        html.push('         <a id="yj_download_sceneDemo" href="javascript:void(0);">下载模板</a>');
        html.push('    </div>');
        html.push(' </div>');
        /*html.push(' <div class="form-group"><label class="col-sm-3 control-label"></label>');
         html.push('    <div class="col-sm-9">');
         html.push('         <a id="yj_download_sceneDemo" href="javascript:void(0);">下载模板</a>');
         html.push('         <button id="scene_cells_inport" class="btn btn-primary">导入场景</button>');
         html.push('    </div>');
         html.push(' </div>');*/
        html.push('</div>');
        var $div = $(html.join(''));
        //绑定地市
        var content = "";
        if (regions != null && regions != undefined && regions.length > 0) {
            for (var i = 0; i < regions.length; i++) {
                var r = regions[i];
                if (city_id == "0") {
                    city_id = r.id;
                }
                content += "<option value='" + r.id + "' neid='" + r.id + "' netype='" + r.type + "'>" + r.name + "</option>";
            }
        }
        content += "<option value='0' neid='0' netype='9000'>全部</option>";
        $div.find("#scene_query_city_select").append($(content));
        $div.find("#scene_query_city_select").change(function () {
            var v = $(this).val();
            city_id = v;
            loadSceneList();
        });

        //绑定场景类型
        loadSceneTypeList();
        //绑定应用专题
        loadSceneAppTopics(function (dat) {
            var content = "";
            if (dat != null && dat != undefined && dat.length > 0) {
                for (var i = 0; i < dat.length; i++) {
                    var r = dat[i];
                    if (i == 0) {
                        content += "<option value='" + r.id + "' selected='selected'>" + r.name + "</option>";
                        select_AppTopics_id = r.id;
                    }
                    else {
                        content += "<option value='" + r.id + "'>" + r.name + "</option>";
                        select_AppTopics_id = r.id;
                    }
                }
            } else {
                content += "<option value='0' selected='selected'>默认</option>";
                select_AppTopics_id = "0";
            }
            $div.find("#scene_query_scene_apptopics_select").append($(content));
            $div.find("#scene_query_scene_apptopics_select").change(function () {
                select_AppTopics_id = $(this).val();
                loadSceneList();
            });

            callback();
        });

        $div.find('._rectangle_btn').on('click', function () {
            if (tempDrawLayer) {
                tempDrawLayer.clear()
            }
            toolbar.activate(esri.toolbars.Draw.RECTANGLE);
            ringType = 1;

        });
        $div.find('._polygon_btn').on('click', function () {
            if (tempDrawLayer) {
                tempDrawLayer.clear()
            }
            //toolbar.activate(esri.toolbars.Draw.FREEHAND_POLYGON);POLYGON
            toolbar.activate(esri.toolbars.Draw.POLYGON);
            ringType = 2;
        });
        $div.find('._line_btn').on('click', function () {
            if (tempDrawLayer) {
                tempDrawLayer.clear()
            }
            toolbar.activate(esri.toolbars.Draw.POLYLINE);
            ringType = 3;
        });
        $div.find("#scene_cells_export").bind("click", function () {
            $.ajax({
                url: "/loadscenedetailcsv",
                data: {
                    scenetypetd: scene_type_id,
                    cityid: city_id,
                    apptopicsid: select_AppTopics_id
                },
                type: "GET",
                dataType: "json",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (req) {
                    gis_common.isLoadingSunCount();
                    gis_common.outPut(req, function (url) {
                        gis_common.windowOpen("pages/export.jsp?typ=application/csv&fid=" + url, "_blank")
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.isLoadingSunCount();
                    gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        });
        $div.find("#scene_cells_inport").bind("click", function () {
            createImportHtml();
        });
        $div.find("#yj_download_sceneDemo").bind("click", function () {
            downloadSceneDemo();
        });
        return $div;
    };
    var loadSceneTypeList = function () {
        if (scene_type_list != null) {
            addSceneType();
        }
        else {
            $.ajax({
                url: "/getscellcenetypelist?r=" + Math.random(),
                type: "GET",
                dataType: "json",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (data) {
                    scene_type_list = data;
                    addSceneType();
                },
                complete: function () {
                    gis_common.isLoadingSunCount();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        }
    };
    var addSceneType = function ($type) {
        if ($type == null || $type == undefined) {
            $type = $('._scene_type');
        }
        if ($type == null || $type == undefined) {
            return;
        }

        if (scene_type_list) {
            $type.append('<option value="0">所有</option>');
            for (var i = 0, len = scene_type_list.length; i < len; i++) {
                $type.append('<option value="' + scene_type_list[i]['scene_type_id'] + '">' + scene_type_list[i]['scene_type_name'] + '</option>');
            }
        }
        $type.change(function () {
            scene_type_id = $(this).val();
            loadSceneList();
        });
    };
    var loadSceneList = function () {
        $.ajax({
            url: "/getcellscenelist?r=" + Math.random(),
            data: {
                sceneid: scene_type_id,
                cityid: city_id,
                apptopicsid: select_AppTopics_id
            },
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    addSceneList(data);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var createImportHtml = function () {
        var html = [];
        html.push('<div id="_up_file_div" class="wrap-cont" style="display: block;padding:20px;">');
        html.push("<div class='row form-group'>");
        html.push("     <a id='yj_download_sceneDemo' href='javascript:void(0);'>下载模板</a>");
        html.push("     <form class='margin-bottom-15'>");
        html.push("     <input id='yj_file' type='file' name='yj_file' />");
        html.push("     <input id='yj_filename' type='hidden' />");
        html.push("     <span id='yj_upload_message'></span>");
        html.push("     <span style='color:red'>温馨提示：文件保存为 utf-8 的编码格式</span>");
        html.push("     </form>");
        html.push("</div>");
        html.push("</div>");
        var divContent = $(html.join(''));
        divContent.find("#yj_download_sceneDemo").bind("click", function () {
            downloadSceneDemo();
        });
        divContent.appendTo($('body'));
        divContent.dialog({
            onclose: function () {
                $("#_up_file_div").remove();
            }
        });
        bind_import_as_file();
    };
    var bind_import_as_file = function () {
        $("#yj_file").uploadify({
            //指定swf文件
            'swf': '/script/base/uploadify/uploadify.swf',
            //后台处理的页面
            'uploader': '/imporscenefile',
            //按钮显示的文字
            'buttonText': '选择上传文件',
            //显示的高度和宽度，默认 height 30；width 120
            //'height': 15,
            //'width': 80,
            //允许上传的文件后缀
            'fileTypeExts': '*.csv',
            //选择文件后自动上传
            'auto': true,
            //设置为true将允许多文件上传
            'multi': false,
            'onUploadSuccess': function (file, data, response) {
                //$('#' + file.id).find('.data').html('导入成功');
                $('#yj_upload_message').html('导入成功');
                gis_common.showMessage("导入成功");
                loadSceneList();
            },
            'onUploadError': function (file, errorCode, errorMsg, errorString) {
                $('#' + file.id).find('.data').html(' 导入失败');
                $('#yj_upload_message').html('导入失败,请检查文件格式');
            }
        });
    }
    var downloadSceneDemo = function () {
        var rul = "/demo/scenedemo.csv";
        gis_common.windowOpen(rul, "_blank");
    };
    var loadSceneAppTopics = function (callback) {
        var appTopics = gis_resources.getCache("apptopics");
        if (appTopics != null && appTopics != "") {
            callback(appTopics);
        }
        else {
            $.ajax({
                url: "/etgsceneapptopics?r=" + Math.random(),
                type: "GET",
                dataType: "json",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (req) {
                    gis_common.outPut(req, function (data) {
                        gis_resources.addCache("apptopics", data);
                        callback(data);
                    });
                },
                complete: function () {
                    gis_common.isLoadingSunCount();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        }
    };

    var onDrawEnd = function (event) {
        rings = event.geometry.rings[0];
        //绘制图层
        drawPolygonGraphic(rings);
        //弹框
        toolbar.deactivate();

        cells = getCellsByRings(rings);

        createSavePolygonHtml();
    };

    var getCellsByRings = function (rings) {

    };

    //创建保存自定义场景html
    var createSavePolygonHtml = function () {
        var html = [];
        html.push('<div id="_polygon_div" class="wrap-cont" style="display: block;padding:20px;">');
        html.push("<div class='row form-group'>");
        html.push("     <label class='col-sm-3 control-label'>场景名称:</label>");
        html.push("     <div class='col-sm-6'>");
        html.push("         <input type='text' maxlength='25' class='form-control _rings_name'/>");
        html.push("     </div>");
        html.push("     <div class='col-sm-3'>(不超过25字)</div>");
        html.push("</div>");
        html.push("<div class='row form-group'>");
        html.push("     <label class='col-sm-3 control-label'>应用专题:</label>");
        html.push("     <div class='col-sm-9'>");
        html.push("         <select id='scene_apptopics' class='form-control'></select>");
        html.push("     </div>");
        html.push("</div>");
        html.push("<div class='row form-group'>");
        html.push("     <label class='col-sm-3 control-label'>场景类型:</label>");
        html.push("     <div class='col-sm-9'>");
        html.push("         <select class='form-control _scene_type'></select>");
        html.push("     </div>");
        html.push("</div>");
        html.push("<div class='row form-group'>");
        html.push("     <label class='col-sm-3 control-label'>小区类型:</label>");
        html.push("     <div class='col-sm-9'>");
        html.push('         <lable style="margin-right: 10px;"><input class="_cell_type" type="checkbox" value="LTE" />4G</lable>');
        html.push('         <lable style="margin-right: 10px;"><input class="_cell_type" type="checkbox" value="TD" />3G</lable>');
        html.push('         <lable><input class="_cell_type" type="checkbox" value="GSM" />2G</lable>');
        html.push("     </div>");
        html.push("</div>");
        //地市
        html.push("<div class='row form-group'>");
        html.push("     <label class='col-sm-3 control-label'>场景所属分公司:</label>");
        html.push("     <div class='col-sm-9'>");
        html.push("         <select id='scene_region_select' class='form-control'>");
        html.push("         </select>");
        html.push("     </div>");
        html.push("</div>");

        html.push("<div class='row form-group'>");
        html.push("     <div class='col-sm-9 col-sm-offset-3'>");
        html.push("		    <button class='btn btn-primary _cell_scene_save_btn'>保 存</button>");
        html.push("	    </div>");
        html.push("</div>");
        html.push('</div>');
        var divContent = $(html.join(''));
        divContent.appendTo($('body'));
        divContent.dialog({
            height: 330,
            onclose: function () {
                tempDrawLayer.clear();
            }
        });

        divContent.find('._cell_scene_save_btn').on('click', function () {
            newSceneId = 0;
            var ringName = divContent.find('._rings_name').val();
            var sceneTypeId = divContent.find('._scene_type').val();
            var sceneTypeName = divContent.find('._scene_type option:selected').text();
            var cellType = [];
            $('._cell_type', divContent).each(function () {
                if (this.checked) {
                    cellType.push($(this).val());
                }
            });
            /*if (cellType.length == 0) {
             gis_common.showError('未选择小区类型');
             return;
             }*/

            //地市
            var selects = divContent.find("#scene_region_select option:selected");
            if (selects != null && selects != undefined) {
                region.id = selects.attr("neid");
                region.type = selects.attr("netype");
                region.name = selects.val();

                select_region_id = region.id;
            } else {
                gis_common.showMessage("请选择地市");
                div.find("#scene_region_select").focus();
                return;
            }

            //应用场景
            var selects_apptopics = divContent.find("#scene_apptopics option:selected");
            if (selects_apptopics != null && selects_apptopics != undefined) {
                select_AppTopics_id = selects_apptopics.val();
                select_AppTopics_name = selects_apptopics.text();
            } else {
                gis_common.showMessage("请选择应用场景");
                div.find("#scene_apptopics").focus();
                return;
            }

            $.ajax({
                url: "/addcellscene?r=" + Math.random(),
                data: {
                    ringName: encodeURIComponent(ringName),
                    rings: JSON.stringify(rings),
                    ringType: ringType,
                    sceneTypeId: sceneTypeId,
                    sceneTypeName: sceneTypeName,
                    area_extend: JSON.stringify(gis_common.getMapExtent()),
                    region: JSON.stringify(region),
                    cells: '',
                    cellType: cellType.join(','),
                    apptopicsid: select_AppTopics_id,
                    apptopicsname: select_AppTopics_name
                },
                type: "POST",
                dataType: "json",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (req) {
                    gis_common.outPut(req, function (data) {
                        if (data > 0) {
                            gis_common.showMessage('保存成功');
                            newSceneId = data;
                            loadSceneList();
                        } else {
                            gis_common.showMessage('保存失败');
                        }
                    });
                },
                complete: function () {
                    divContent.dialog('close');
                    gis_common.isLoadingSunCount();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        });


        var $type = $('._scene_type', divContent);
        if (scene_type_list) {
            for (var i = 0, len = scene_type_list.length; i < len; i++) {
                $type.append('<option value="' + scene_type_list[i]['scene_type_id'] + '">' + scene_type_list[i]['scene_type_name'] + '</option>');
            }
        }
        //绑定地市信息
        gis_resources.getRegions(function (data) {
            var content = "";
            if (data != null && data != undefined && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var r = data[i];
                    if ((select_region_id == null && i == 0) || select_region_id == r.id) {
                        content += "<option neid='" + r.id + "' netype='" + r.type + "' selected='selected'>" + r.name + "</option>";
                    }
                    else {
                        content += "<option neid='" + r.id + "' netype='" + r.type + "'>" + r.name + "</option>";
                    }
                }
            } else {
                content += "<option neid='1' netype='9000' selected='selected'>全部</option>";
            }
            divContent.find("#scene_region_select").append($(content));
        });
        //绑定应用专题
        loadSceneAppTopics(function (data) {
            var content = "";
            if (data != null && data != undefined && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var r = data[i];
                    if ((select_AppTopics_id == null && i == 0) || (select_AppTopics_id == r.id)) {
                        content += "<option value='" + r.id + "' selected='selected'>" + r.name + "</option>";
                    }
                    else {
                        content += "<option value='" + r.id + "'>" + r.name + "</option>";
                    }
                }
            } else {
                content += "<option value='0' selected='selected'>默认</option>";
            }
            divContent.find("#scene_apptopics").append($(content));
        });

    };

    //添加自定义场景
    var addSceneList = function (data) {
        var $list = $('._cell_scene_list');
        $list.empty();
        for (var i = 0, len = data.length; i < len; i++) {
            var $button = $('<button type="button" class="list-group-item _cell_scene_item _list_item_' + data[i]["scene_id"] + '">' +
                '<a href="javascript:;" style="float: right;margin-left:5px;"><i class="fa fa-remove _btn_del" title="删除" ></i></a>' +
                '<span></span>' +
                '</button>');

            $button.attr({
                'pid': data[i]['scene_id'],
                'tid': data[i]['scene_type_id'],
                'celltypes': data[i]['cellTypes']
            }).data('rings', data[i]['range']);

            $button.find('span').html(data[i]['scene_name']);
            $button.click(function () {
                if (tempDrawLayer) {
                    tempDrawLayer.clear()
                }

                var typs = "celltypes:" + $(this).attr("celltypes");
                var sceneid = $(this).attr("pid");

                var ring = $(this).data('rings');
                if (!gis_common.stringIsNullOrWhiteSpace(ring)) {
                    drawPolygonGraphic(JSON.parse(ring));
                }

                //开始去场景小区
                $.ajax({
                    url: "/getcellrefscenelist?r=" + Math.random(),
                    data: {sceneid: sceneid},
                    type: "GET",
                    dataType: "json",
                    beforeSend: function () {
                        gis_common.isLoadingAddCount();
                    },
                    success: function (req) {
                        gis_common.outPut(req, function (data) {
                            if (data != null && data != "") {
                                var xmax;
                                var ymax;
                                var xmin;
                                var ymin;

                                for (var i = 0; i < data.length; i++) {
                                    var d = data[i];
                                    var graphic = gis_common.createCellGraphic(d);
                                    tempDrawLayer.add(graphic);

                                    if (!xmax || xmax < d.longitude) {
                                        xmax = d.longitude;
                                    }
                                    if (!ymax || ymax < d.latitude) {
                                        ymax = d.latitude;
                                    }
                                    if (!xmin || xmin > d.longitude) {
                                        xmin = d.longitude;
                                    }
                                    if (!ymin || ymin > d.latitude) {
                                        ymin = d.latitude;
                                    }
                                }

                                if (xmax && ymax && xmin && ymin) {
                                    gis_common.setExtent(xmax + 0.005, ymax + 0.005, xmin - 0.005, ymin - 0.005);
                                }
                            }
                        });
                    },
                    complete: function () {
                        gis_common.isLoadingSunCount();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                    }
                });


                /*var RqCell = {
                 gsm: false,
                 td: false,
                 lte: false,
                 alonecell: 0,
                 region: {
                 id: 1,
                 type: 9000
                 }
                 };
                 if (typs.indexOf("LTE") > 0) {
                 RqCell.lte = true;
                 }
                 if (typs.indexOf("GSM") > 0) {
                 RqCell.gsm = true;
                 }
                 if (typs.indexOf("TD") > 0) {
                 RqCell.td = true;
                 }
                 gis_common.resSetQueryParam(RqCell);

                 $(this).addClass('active').siblings().removeClass('active');
                 drawPolygonGraphic(JSON.parse($(this).data('rings')));*/
            });

            var $del = $button.find('._btn_del');
            $del.attr('tid', data[i]['scene_id']);
            $del.click(function (event) {
                if (confirm('确认删除？')) {
                    deleteScene($(this).attr('tid'));
                    $(this).parent().parent().remove();
                    if ($('._cell_scene_item.active').length == 0) {
                        tempDrawLayer.clear();
                    }
                }
                event.stopPropagation();
            });

            $button.appendTo($list);
        }

        if (newSceneId != 0) {
            $list.find('._list_item_' + newSceneId).click();
            newSceneId = 0;
        }
    };

    //删除自定义场景
    var deleteScene = function (tid) {
        $.ajax({
            url: "/delcellscene?r=" + Math.random(),
            data: {id: tid},
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {

                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var drawPolygonGraphic = function (rings) {
        if (rings == null || rings == "" || rings.length == 0) {
            return;
        }
        var polygon = new esri.geometry.Polygon(new esri.SpatialReference({wkid: 4326}));
        //添加多边形的各个角的顶点坐标，注意：首尾要链接，也就是说，第一个点和最后一个点要一致
        polygon.addRing(rings);
        var symbol = new esri.symbol.SimpleFillSymbol().setColor(new esri.Color([180, 168, 192, 0.2])).setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([200, 112, 181, 0.9]), 1));
        var graphic = new esri.Graphic(polygon, symbol);
        tempDrawLayer.add(graphic);
        offsetMainLayer(rings);
    };

    //偏移底图
    var offsetMainLayer = function (rings) {
        var xmax;
        var ymax;
        var xmin;
        var ymin;
        for (var i = 0, len = rings.length; i < len; i++) {
            var item = rings[i];
            if (!xmax || xmax < item[0]) {
                xmax = item[0];
            }

            if (!ymax || ymax < item[1]) {
                ymax = item[1];
            }

            if (!xmin || xmin > item[0]) {
                xmin = item[0];
            }

            if (!ymin || ymin > item[1]) {
                ymin = item[1];
            }
        }

        if (xmax && ymax && xmin && ymin) {
            gis_common.setExtent(xmax + 0.005, ymax + 0.005, xmin - 0.005, ymin - 0.005);
        }
    };

    this.createSceneHolderDiv = function (callback) {
        gis_resources.getRegions(function (data) {
            regions = data;
            var content = createSceneHolderHtml(function () {
                loadSceneList();
            });
            callback(content);
        });
    };

    this.init = function () {
        dojo.require("esri.layers.WMSLayerInfo");
        dojo.require("esri.layers.WMSLayer");
        dojo.require("esri.toolbars.draw");
        tempDrawLayer = gis_core.addGraphicsLayerWithIndex('cell_scene_draw_layer', '区域框选', 2);

        toolbar = new esri.toolbars.Draw(gis_core.map, {
            tooltipOffset: 20,
            drawTime: 90,
            showTooltips: true
        });
        toolbar.on("draw-end", onDrawEnd);
    };
}

/***keyValue 类
 */
function KeyValues() {
    this.values = new Array();
    var struct = function (key, value) {
        this.key = key;
        this.value = value;
    };
    this.lookUp = function (key) {
        for (var i = 0; i < this.values.length; i++) {
            if (this.values[i].key === key) {
                return this.values[i].value;
            }
        }
        return null;
    };
    this.setAt = function (key, value) {
        for (var i = 0; i < this.values.length; i++) {
            if (this.values[i].key === key) {
                this.values[i].value = value;
                return;
            }
        }
        this.values[this.values.length] = new struct(key, value);
    };
    this.removeKey = function removeKey(key) {
        var v;
        for (var i = 0; i < this.values.length; i++) {
            v = this.values.pop();
            if (v.key === key)
                continue;

            this.values.unshift(v);
        }
    };
    this.index = function (i) {
        if (i >= this.getCount) {
            return null
        } else {
            return this.values[i].value;
        }
    };
    this.containsKey = function (key) {
        var f = false;
        for (var i = 0; i < this.values.length; i++) {
            if (this.values[i].key === key) {
                f = true;
                break;
            }
        }
        return f;
    }
    this.getCount = function () {
        return this.values.length;
    };
    this.isEmpty = function () {
        return this.values.length <= 0;
    };
    this.clear = function () {
        this.values = new Array();
    };
}

function init() {
    gis_core.initMap(function () {
        gis_common.queryInit();
        initgis();
    });
}

// 程序入口
$(function () {
    var data = {};
    var m = gis_common.getQueryString("m");
    if (!gis_common.stringIsNullOrWhiteSpace(m)) {
        data.m = m;
    }

    $.ajax({
        url: "/getinitconfig",
        dataType: "json",
        data: data,
        /*  async: true,*/
        type: "GET",
        beforeSend: function () {
            gis_common.isLoadingAddCount();
        },
        success: function (req) {
            gis_common.outPut(req, function (initconfig) {
                //var initconfig = eval(req);
                gis_core.initconfig = initconfig;
                init();
            });
        },
        complete: function () {
            gis_common.isLoadingSunCount();
        },
        error: function () {
        }
    });
});
